在 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
绑定到TreeView
xaml 中的控件。当它更新时,我想调用一个更新属性的方法Conditions
。此属性绑定到TextBox
xaml 中的 a。
我是 C# Eventing 的新手,所以有点迷茫。
编辑
- 类
TreeViewModel
实现INotifyPropertyChanged
。 Conditions
通过从 中获取IsChecked
值来更新TreeView
。- 状态列表的大小永远不会改变。When a TreeViewItem is selected/unselected the TreeViewModel changes.
- TreeViewModel 源(此页面上的 FooViewModel )
- 上面的绑定代码。
不必为
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>