首页 文章

WPF派生的ComboBox SelectedValuePath问题

提问于
浏览
3

在我们的应用程序中,我们有一个非常大的数据集作为我们的ComboBox列表等的数据字典 . 这些数据是静态缓存的,并且由2个变量键入,所以我认为编写一个派生自ComboBox并暴露的控件是明智的 . 2个键作为DP . 当这两个键具有适当的值时,我自动从它对应的数据字典列表中设置ComboBox的ItemsSource . 我还自动将构造函数中的SelectedValuePath和DisplayMemberPath分别设置为Code和Description .

以下是数据字典列表中ItemsSource中的项目如何始终显示的示例:

public class DataDictionaryItem
{
    public string Code { get; set; }
    public string Description { get; set; }
    public string Code3 { get { return this.Code.Substring(0, 3); } }
}

Code的值总是4个字符长,但有时我只需要绑定3个字符 . 因此,Code3属性 .

以下是代码在我的自定义组合框中查看以设置ItemsSource的方式:

private static void SetItemsSource(CustomComboBox combo)
{
    if (string.IsNullOrEmpty(combo.Key1) || string.IsNullOrEmpty(combo.Key2))
    {
        combo.ItemsSource = null;
        return;
    }

    List<DataDictionaryItem> list = GetDataDictionaryList(combo.Key1, combo.Key2);
    combo.ItemsSource = list;
}

现在,我的问题是,当我将XAML中的SelectedValuePath更改为Code3时,它不起作用 . 我绑定到SelectedValue的内容仍然从DataDictionaryItem获取完整的4个字符代码 . 当SelectedValuePath被更改并且没有骰子时,我甚至尝试重新运行SetItemsSource .

任何人都可以看到我需要做什么来让我的自定义组合框唤醒并使用提供的SelectedValuePath,如果它在XAML中被覆盖?在SelectedValue绑定业务对象中调整属性setter中的值不是一个选项 .

以下是XAML在表单中查找组合框的方式:

<c:CustomComboBox Key1="0" Key2="8099" SelectedValuePath="Code3" SelectedValue="{Binding Thing}"/>

EDIT :我刚刚对我的代码进行了窥探,它说我的SelectedValuePath是Code ...它似乎没有被设置为Code3 ...... Zuh?

1 回答

  • 4

    好的,我明白了 .

    显然在WPF控件的默认非静态构造函数中设置DependencyProperty的默认值是禁忌 . 所以,起初我试过这个:

    static ValueCodeListComboBox()
    {
      SelectedValuePathProperty.OverrideMetadata(typeof(ValueCodeListComboBox), new PropertyMetadata("Code"));
      DisplayMemberPathProperty.OverrideMetadata(typeof(ValueCodeListComboBox), new PropertyMetadata("Description"));
    }
    

    但这一直在抛出错误说:

    元数据覆盖和基本元数据必须是相同类型或派生类型 .

    最后发现这意味着我需要使用FrameworkPropertyMetadata而不是PropertyMetadata:

    static ValueCodeListComboBox()
    {
      SelectedValuePathProperty.OverrideMetadata(typeof(ValueCodeListComboBox), new FrameworkPropertyMetadata("Code"));
      DisplayMemberPathProperty.OverrideMetadata(typeof(ValueCodeListComboBox), new FrameworkPropertyMetadata("Description"));
    }
    

    现在,在XAML中更改SelectedValuePath非常有效 .

相关问题