2017-04-13 72 views
1

我有一個用戶控件在WPF中,我想傳遞一個項目列表,當我在另一個窗口中使用用戶控件(用戶控件包含一個組合框和標籤,並具有一些重要的功能)。這工作正常,如果我有我的網頁上的單個控件,但如果我有兩個我從兩個我的用戶控件列出值,大概是因爲DependencyProperty是靜態的。我無法刪除靜態,因爲它在註冊依賴項屬性時引發錯誤。WPF依賴項屬性ObservableCollection顯示多個值

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); } 
} 

下面顯示了一個包含值1和值2

<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); } 
    } 

} 

回答

2

你應該在的構造函數初始化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

+0

完美,感謝您的快速回復。很棒! – Cookie