[英]WPF call method when property changes
在C#中,如何在屬性更改時調用方法(方法和屬性都屬於同一個類)?
例如,
class BrowserViewModel
{
#region Properties
public List<TreeViewModel> Status { get; private set; }
public string Conditions { get; private set; }
#endregion // Properties
// i'd like to call this method when Status gets updated
void updateConditions
{
/* Conditions = something depending on the TreeViewItem select status */
}
}
捆綁
<TreeView Grid.Row="1"
x:Name="StatusTree"
ItemContainerStyle="{StaticResource TreeViewItemStyle}"
ItemsSource="{Binding Path=Status, Mode=OneTime}"
ItemTemplate="{StaticResource CheckBoxItemTemplate}"
/>
用例 (如果你很好奇)
屬性Status
綁定到xaml中的TreeView
控件。 更新后,我想調用一個更新屬性Conditions
。 此屬性綁定到xaml中的TextBox
。
我是C#中Eventing的新手,所以有點迷失。
TreeViewModel
實現了INotifyPropertyChanged
。 TreeView
獲取IsChecked
值來更新Conditions
。 沒有必要更改IsChecked
綁定模式。
<HierarchicalDataTemplate x:Key="CheckBoxItemTemplate" ItemsSource="{Binding Children, Mode=OneTime}" > <StackPanel Orientation="Horizontal"> <!-- These elements are bound to a TreeViewModel object. --> <CheckBox Focusable="False" IsChecked="{Binding IsChecked}" VerticalAlignment="Center" /> <ContentPresenter Content="{Binding Name, Mode=OneTime}" Margin="2,0" /> </StackPanel> </HierarchicalDataTemplate>
我假設您希望updateConditions
在列表中添加/刪除/更改item
時觸發,而不是列表引用本身更改時觸發。
由於您在TreeViewModel中實現了INotifyPropertyChanged,我認為您將要使用ObservableCollection<T>
而不是普通的List<T>
。 請在此處查看: http : //msdn.microsoft.com/en-us/library/ms668604.aspx
表示動態數據集合,在添加,刪除項目或刷新整個列表時提供通知。
class BrowserViewModel
{
#region Properties
public ObservableCollection<TreeViewModel> Status { get; private set; }
public string Conditions { get; private set; }
#endregion // Properties
// i'd like to call this method when Status gets updated
void updateConditions
{
/* Conditions = something */
}
public BrowserViewModel()
{
Status = new ObservableCollection<TreeViewModel>();
Status.CollectionChanged += (e, v) => updateConditions();
}
}
每當添加/刪除/更改項目時,CollectionChanged都將觸發。 據我所知,當引用更改或其任何屬性發生更改時(通過INotifyPropertyChanged
通知),它會認為它已“更改”
只需在此處查看: http : //msdn.microsoft.com/en-us/library/ms653375.aspx
ObservableCollection.CollectionChanged事件在添加,刪除,更改,移動項目或刷新整個列表時發生。
ObservableCollection<T>
駐留在System.dll
程序集中的System.Collections.ObjectModel
命名空間中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.