2016-10-31 36 views
0

我創建了一個用戶控件(FilterPicker),它具有某個列表作爲屬性。這是一個依賴項屬性,因此可以在使用用戶控件時進行設置。從XAML(WPF)設置集合DependencyProperty

public static readonly DependencyProperty StrategiesProperty = DependencyProperty.Register(
     "Strategies", 
     typeof(List<FilterType>), 
     typeof(FilterPicker), 
     new FrameworkPropertyMetadata 
     { 
      DefaultValue = new List<FilterType> { FilterType.Despike }, 
      PropertyChangedCallback = StrategiesChangedCallback, 
      BindsTwoWayByDefault = false, 
     }); 

然後我試圖在我使用這個控件的.xaml文件中定義這個列表。

<Filtering:FilterPicker Grid.Row="1" Strategy="{Binding Strategy}"> 
      <Filtering:FilterPicker.Strategies> 
       <Filtering1:FilterType>PassThrough</Filtering1:FilterType> 
       <Filtering1:FilterType>MovingAverage</Filtering1:FilterType> 
       <Filtering1:FilterType>Despike</Filtering1:FilterType> 
      </Filtering:FilterPicker.Strategies> 
     </Filtering:FilterPicker> 

但是,它不起作用。 StrategiesChangedCallBack永遠不會被調用。 如果我通過綁定來設置它,它工作正常 - 只是當我嘗試在xaml中定義它時。所以這個作品:

<Filtering:FilterPicker Grid.Row="1" Strategy="{Binding Strategy}" Strategies="{Binding AllStrategies}"> 

但不是以前的代碼片段。關於我在做什麼的任何想法都是錯誤的?

+3

在XAML中添加的元素被添加到現有的集合,它已設置爲屬性的默認值。集合實例不會更改,因此不會調用PropertyChangedCallback。您可以使用實現INotifyCollectionChanged接口(例如ObservableCollection)的集合,併爲其CollectionChanged事件附加處理程序,而不是List。 – Clemens

+1

除此之外,對集合類型依賴項屬性使用默認值有潛在危險,因爲擁有的類的所有實例將默認在相同的集合實例上操作,即向一個FilterPicker的Strategies屬性中添加元素將影響屬性所有其他FilterPickers。 – Clemens

+0

有關如何處理INotifyCollectionChanged,請參閱示例[此答案](http://stackoverflow.com/a/9128855/1136211)或[this one](http://stackoverflow.com/a/19558932/1136211)。 – Clemens

回答

1

從我原來的問題的評論,我能夠拼湊一起:

  • 事實上,問題是,我只是聽着財產被改變,而不是集合中的對象。
  • 正如我預測的那樣,它在同一個集合實例上運行時遇到問題。

最後,我將我的DependencyProperty更改爲使用IEnumerable,我在使用FilterPicker UserControl的.xaml中將其定義爲StaticResource。

的DependencyProperty:

public static readonly DependencyProperty StrategiesProperty = DependencyProperty.Register(
     "Strategies", 
     typeof(IEnumerable<FilterType>), 
     typeof(FilterPicker), 
     new FrameworkPropertyMetadata 
     { 
      DefaultValue = ImmutableList<FilterType>.Empty, //Custom implementation of IEnumerable 
      PropertyChangedCallback = StrategiesChangedCallback, 
      BindsTwoWayByDefault = false, 
     }); 

使用它:

<Grid.Resources> 
      <x:Array x:Key="FilterTypes" Type="{x:Type Filtering1:FilterType}" > 
       <Filtering1:FilterType>PassThrough</Filtering1:FilterType> 
       <Filtering1:FilterType>MovingAverage</Filtering1:FilterType> 
       <Filtering1:FilterType>Fir</Filtering1:FilterType> 
      </x:Array> 
     </Grid.Resources> 

<Filtering:FilterPicker Grid.Row="1" Strategies="{StaticResource FilterTypes}" /> 
相關問題