3

在 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绑定到TreeViewxaml 中的控件。当它更新时,我想调用一个更新属性的方法Conditions。此属性绑定到TextBoxxaml 中的 a。

我是 C# Eventing 的新手,所以有点迷茫。

编辑

  1. TreeViewModel实现INotifyPropertyChanged
  2. Conditions通过从 中获取IsChecked值来更新TreeView
  3. 状态列表的大小永远不会改变。When a TreeViewItem is selected/unselected the TreeViewModel changes.
  4. TreeViewModel 源(此页面上的 FooViewModel )
  5. 上面的绑定代码。
  6. 不必为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>
    
4

1 回答 1

8

我假设您想在列表中添加/删除/更改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.Collections.ObjectModel名称空间中,在System.dll程序集中。

于 2013-04-11T14:25:24.640 回答