2011-04-18 42 views
1

我有一個列表框,其中的item源包含一個List(T),它具有SelectedFlag布爾屬性。我的viewmodel被設置爲我的用戶控件的DataContext,並且所有內容都按預期工作,除非我在更改複選框時無法獲取屬性更改。IsChecked上的UpdateSourceTrigger PropertyChanged不是在複選框的ListBox的ItemsSource上觸發

這是我的XAML列表框

<ListBox x:Name="lstRole" ItemsSource="{Binding Path=FAccountFunctions, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" SelectedValuePath="Id"> 
       <ListBox.ItemTemplate> 
        <DataTemplate> 
         <StackPanel Orientation="Horizontal"> 
          <CheckBox IsChecked="{Binding Path=SelectedFlag, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Center" /> 
          <TextBlock Text="{Binding Path=FunctionDesc}" VerticalAlignment="Center" /> 
         </StackPanel> 
        </DataTemplate> 
       </ListBox.ItemTemplate> 
      </ListBox> 

我需要調用我的過濾器()函數檢查後一個複選框,我通常會設置UpdateSourcTrigger =的PropertyChanged,使這項工作。

Public Property FAccountFunctions As List(Of FunctionType) 
     Get 
      Return _faccountFunctions 
     End Get 
     Set(ByVal value As List(Of FunctionType)) 
      _faccountFunctions = value 
      Filter() 
     End Set 
    End Property 

PropertyChangedEvent在FAccountFunctions集合的'SelectedFlag'屬性中引發。當其中一個屬性SelectedFlag更改時,如何在項目源上引發事件?

將我的FAccountFunctions屬性更改爲ObservableCollection ...沒有運氣。

回答

2

當您的Item的PropertyChanged事件觸發時,您需要使Collection的CollectionChanged事件觸發。

喜歡的東西:

MyCollection.CollectionChanged += MyCollectionChanged; 

...

void MyCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) 
{ 
    if (e.NewItems != null) 
    { 
     foreach (object item in e.NewItems) 
     { 
      if (item is MyItem) 
       ((MyItem)item).PropertyChanged += MyItem_PropertyChanged; 
     } 
    } 

    if (e.OldItems != null) 
    { 
     foreach (object item in e.OldItems) 
     { 
      if (item is MyItem) 
       ((MyItem)item).PropertyChanged -= MyItem_PropertyChanged; 
     } 
    } 
} 

...

void MyItem_PropertyChanged(object sender, PropertyChangedEventArgs e) 
{ 
    OnPropertyChanged("MyCollection"); 
} 
+0

謝謝您的回答!我實現了你的解決方案,但MyCollectionChanged沒有被調用。在集合加載之前,我在ViewModel的構造函數中添加了AddHandler FAccountFunctions.CollectionChanged,AddressOf MyCollectionChanged。因爲這個MyItem_PropertyChanged永遠不會被調用。我可能不得不在我的代碼中使用Checked事件: – knockando 2011-04-19 14:24:44

+1

@knockando您是否在爲MyCollection使用ObservableCollection?並且是否在創建ObservableCollection之前附加了CollectionChanged事件?如果您之後創建的是新對象, t附加了Changed事件。 – Rachel 2011-04-19 14:43:37

相關問題