我在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); }
}
}
答案 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