簡體   English   中英

屬性更改時的WPF調用方法

[英]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的新手,所以有點迷失。

編輯

  1. class TreeViewModel實現了INotifyPropertyChanged
  2. 通過從TreeView獲取IsChecked值來更新Conditions
  3. 狀態列表的大小永遠不會改變。 選擇/取消選擇TreeViewItem時,TreeViewModel會更改。
  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> 

我假設您希望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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM