WPF依赖项属性ObservableCollection显示多个值

时间:2017-04-13 10:22:50

标签: c# wpf user-controls

我在WPF中有一个用户控件,当我在另一个窗口中使用用户控件时,我想传递一个项目列表(用户控件包含一个ComboBox和标签,并具有一些重要的功能)。如果我的页面上有一个控件,这可以正常工作,但如果我有两个控件,我会从我的两个用户控件中列出值,大概是因为DependencyProperty是静态的。我无法删除静态,因为它在注册依赖项属性时会抛出错误。

public static readonly DependencyProperty ComboBoxValuesProperty =
    DependencyProperty.Register("ComboBoxValues", typeof(ObservableCollection<ComboBoxValue>), typeof(SystemConfigComboBox),
    new PropertyMetadata(new ObservableCollection<ComboBoxValue>()));

public ObservableCollection<ComboBoxValue> ComboBoxValues
{
    get { return GetValue(ComboBoxValuesProperty) as ObservableCollection<ComboBoxValue>; }
    set { SetValue(ComboBoxValuesProperty, value); }
}

下面显示了包含Value1和Value2

的用户控件组合框
<customEditors:SystemConfigComboBox SystemConfigEntry="Entry1" ComboBoxLabel="Combo 1" ComboBoxWidth="300">
    <customEditors:SystemConfigComboBox.ComboBoxValues>
        <customEditors:ComboBoxValue DisplayValue="Value1" ActualValue="VALUE1" />
    </customEditors:SystemConfigComboBox.ComboBoxValues>
</customEditors:SystemConfigComboBox>
<customEditors:SystemConfigComboBox SystemConfigEntry="Entry2" ComboBoxLabel="Combo 2" ComboBoxWidth="300">
    <customEditors:SystemConfigComboBox.ComboBoxValues>
        <customEditors:ComboBoxValue DisplayValue="Value2" ActualValue="VALUE2" />
    </customEditors:SystemConfigComboBox.ComboBoxValues>
</customEditors:SystemConfigComboBox>

仅供参考ComboBoxValue类: -

public class ComboBoxValue : FrameworkElement
{
    public static readonly DependencyProperty DisplayValueProperty =
        DependencyProperty.Register("DisplayValue", typeof(string), typeof(ComboBoxValue));

    public static readonly DependencyProperty ActualValueProperty =
        DependencyProperty.Register("ActualValue", typeof(string), typeof(ComboBoxValue));

    public string DisplayValue
    {
        get { return (string)GetValue(DisplayValueProperty); }
        set { SetValue(NameProperty, value); }
    }

    public string ActualValue
    {
        get { return (string)GetValue(ActualValueProperty); }
        set { SetValue(ActualValueProperty, value); }
    }

}

1 个答案:

答案 0 :(得分:3)

您应该在控件类的构造函数中初始化ObservableCollection而不是DependencyProperty.Register方法:

public class SystemConfigComboBox
{
    public SystemConfigComboBox()
    {
        ComboBoxValues = new ObservableCollection<ComboBoxValue>();
    }

    public static readonly DependencyProperty ComboBoxValuesProperty =
            DependencyProperty.Register("ComboBoxValues", typeof(ObservableCollection<ComboBoxValue>), typeof(SystemConfigComboBox)));

    ...
}

有关详细信息,请参阅MSDN:https://msdn.microsoft.com/en-us/library/aa970563(v=vs.110).aspx