![](/img/trans.png)
[英]How to add a new property to an existing json without defining model class in C#?
[英]How to add a new property to model-class without extending it in MVVM
我的視圖包含一個 ListView(ItemsSource 是一個 ObservableCollection),我想將項目顯示為帶有一些文本的復選框(綁定到我的模型類的名稱屬性)。 到目前為止這沒有問題,但我很難決定將“IsChecked” -屬性放置在哪里,我需要綁定到(知道哪些項目已被檢查)。
我可以將它添加到我的模型類中,但這感覺不正確,我不想“污染”我的 model。 我的另一個想法是擴展導致新文件的模型類,但這感覺也不對。 有什么建議么?
看法
<ListView ItemsSource="{Binding CustomerCollection}">
<ListView.ItemTemplate>
<DataTemplate>
<DockPanel>
<CheckBox Foreground="Black"/>
<TextBlock Text="{Binding Name}"/>
</DockPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
視圖模型
private ObservableCollection<Customer> customerCollection = LoadCustomerCollection();
public ObservableCollection<Customer> CustomerCollection { get => customerCollection; set => customerCollection = value; }
模型類:
public class Customer : INotifyPropertyChanged
{
private int id;
public int Id
{
get { return id; }
set
{
if(value != this.id)
{
id = value;
NotifyPropertyChanged("Id");
}
}
}
private string name;
public string Name
{
get { return name; }
set
{
if(value != this.name)
{
name = value;
NotifyPropertyChanged("Name");
}
}
}
protected virtual void NotifyPropertyChanged(String propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
我對 MVVM 的看法是:-
Model類只保存數據,一個 model 實例對應於數據表中的一條記錄。
包裝 ViewModel類與 model 類並行存在以保存非數據屬性(例如您的情況下的 IsSelected ),以及 Model 實例之間的鏈接,例如父子關系。 包裝器視圖模型將 model class 實例作為屬性公開,因此您可以直接綁定到模型的屬性,而不必在包裝器上創建外觀屬性。
標准 ViewModel類是 View 的主要控制器和數據提供者。
有關這一點的更詳細討論,請參閱我的博客文章。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.