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

标签 wpf xaml binding combobox

我的 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/

相关文章:

c# - 如何将报表查看器语言设置为与 CultureInfo.CurrentUICulture 相同?

wpf - 使用 WrapPanel 和 ScrollViewer 在 WPF 中给出多列列表框

c# - 在 WPF 中使 StackPanel 方向水平

c# - 在另一台机器上运行 Windows 8.1 应用程序

java - 具有多个端点的 Azure 函数 (Java)

binding - 包装器、绑定(bind)和端口之间有什么区别?

c# - 如何通知父类有关属性更改

c# - 在单独的进程中从插件获取 WPF 应用程序中的 TextBox 焦点

wpf - 删除列表框周围的多余空间

c# - 多个 View 模型共享一个带有通知的服务