gpt4 book ai didi

WPF ComboBox 在是 DependencyObject 时不显示当前项目

转载 作者:行者123 更新时间:2023-12-04 13:51:17 25 4
gpt4 key购买 nike

我的 XAML 中有这个非常简单的组合框:

<ComboBox Name="cmb1" Width="200" Height="23" ItemsSource="{Binding}" />

这是我背后的代码:
public class Test //: System.Windows.DependencyObject
{
public string Name { get; set; }

public override string ToString() { return Name; }
}

public MainWindow()
{
InitializeComponent();

var col = new ObservableCollection<Test>();
cmb1.DataContext = col;
col.Add(new Test { Name = "A" });
col.Add(new Test { Name = "B" });
col.Add(new Test { Name = "C" });
col.Add(new Test { Name = "D" });
}

只要 测试 类不是从 继承的依赖对象 一切安好。但是继承的时候,ComboBox 不展开时不显示当前项。
当我单击 ComboBox 并查看其下拉框时,选择了当前项目。
alt text

最佳答案

这是 karmicpuppet 的回答在一个现已删除的问题中:

This is interesting. Well, I've looked at the ComboBox class using Reflector and I see that in the ComboBox.UpdateSelectionBoxItems() method, part of it does something like:

If ItemTemplate, ItemTemplateSelector, and ItemStringFormat were not set, and selected item is a DependencyObject that is not derived from UIElement, call the ExtractString(selectedItem) method.

The ComboBox.ExtractString(dObj) method, on the other hand, apparently checks to see if the selectedItem (which is a DependencyObject) is either a TextBlock, a Visual, or a TextElement to display the appropriate string. Otherwise, it will return string.Empty.



所以最简单的解决方案是在组合框上设置它:
ItemStringFormat="{}{0}"

关于WPF ComboBox 在是 DependencyObject 时不显示当前项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3786093/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com