[英]wpf binding upwards: bind to view model property inside nested uiElement
[英]Nested view model in WPF
仍然嘗試在此處學習MVVM和WPF。
我正在嘗試創建一個復雜的視圖模型EditArticleViewModel
。 它有一些針對相似控件重復的代碼,因此我將重復的代碼移到了另一個類中。 然后,我將另一個類的幾個實例添加到EditArticleViewModel
。
我將把EditArticleViewModel
的實例設置為窗口的DataContext
。 我將綁定到Categories.Items
和Subcategories.SelectedItem
類的東西。
public class CategoryView
{
public ObservableCollection<object> Items { /* */ }
public object SelectedItem { /* ... */ }
}
public class SubcategoryView
{
public ObservableCollection<object> Items { /* */ }
public object SelectedItem { /* ... */ }
}
public class EditArticleViewModel : INotifyPropertyChanged
{
public CategoryView Categories { get; private set; }
public SubcategoryView Subcategories { get; private set; }
public EditArticleViewModel()
{
Categories = new CategoryView();
SubcategoryView Subcategories new SubcategoryView();
}
// Additional properties and methods here
}
如您所見,我的EditArticleViewModel
類實現了INotifyPropertyChanged
以便在發生更改時可以通知可視元素。
我的問題是關於如何通知視覺元素有關CategoryView
和SubcategoryView
更改的信息。 有沒有一種方法可以直接向窗口通知這些類中的更改? 還是我必須從每個類中引發一個事件並讓EditArticleViewModel
處理該事件才能發送適當的通知?
任何提示表示贊賞。
每個視圖只能有一個ViewModel,並且擴展方式是主ViewModel可以包含其他“ ViewModel”。
因此,當您將DataContext
設置為主ViewModel時,其所有內容將具有對NotifyPropertyChanged
事件的訂閱,因此將通知在其他派生的ViewModel中實現INotifyPropertyChanged
接口。
我建議使用INotifyPropertyChanged
interface
實現基類,您可以從其他ViewModel中派生該interface
。
通過進行此更改,您應該解決您遇到的問題:
public class ObservableViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged([CallerMemberName]string propName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
}
}
public class CategoryView : ObservableViewModelBase
{
public ObservableCollection<object> Items { /* */ }
public object SelectedItem { /* ... */ }
}
public class SubcategoryView : ObservableViewModelBase
{
public ObservableCollection<object> Items { /* */ }
public object SelectedItem { /* ... */ }
}
public class EditArticleView : ObservableViewModelBase
{
public CategoryView Categories { get; set; } = new CategoryView();
public SubcategoryView Subcategories { get; set; } = new SubcategoryView();
}
關於ObservableCollection
。 僅當您添加/刪除項目時,它才會通知視圖更改,但是當內容更改時,它不會通知。 要更新有關項目內容更改的視圖,您應該具有以下內容:
public class GridRowItemViewModel : ObservableViewModelBase // From previous example.
{
private string _sampleProp;
public string SampleProp
{
get
{
return _sampleProp;
}
set
{
_sampleProp = value;
OnPropertyChanged();
}
}
}
因此,您的Main ViewModel應該看起來像這樣:
public class MainViewModel : ObservableViewModelBase // This is your DataContext.
{
public ObservableCollection<GridRowItemViewModel> GridCollection { get; set; }
}
編輯:您不能綁定到字段,WPF不能解析字段。 它只能處理屬性。 因此,通過創建子ViewModel的純字段,您將無處可尋。 將它們更改為屬性,您將可以通過屬性名稱在視圖中訪問其內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.