[英]How update List of datagrid c# wpf caliburn.micro
在這堂課:
[Export(typeof(IScreen))]
public class BolleViewModel : Screen
{
....
}
我有這個清單:
public List<Article> List { get; private set; }
此列表是Datagrid與List的綁定:
<DataGrid HorizontalAlignment="Stretch" SelectedItem="{Binding SelectedArticle}"
Margin="14,41,12,61" VerticalAlignment="Stretch" AutoGenerateColumns="False" x:Name="List">
我想在調用方法UPDATE時更新List和Datagrid的值。 這是我的更新方法:
public void Update(List<Article> list)
{
List = list;
NotifyOfPropertyChange("List");
}
我錯了什么? ?
Caliburn.Micro不支持開箱即用的基於約定的DataGrid
綁定,你可以通過檢查ConventionManager
靜態構造函數來看到這一點。
您可以使用ConventionManager
編寫自己的約定,也可以在視圖中設置ItemsSource
屬性綁定。
例如
<DataGrid ItemsSource="{Binding Articles}" SelectedItem="{Binding SelectedArticle}"
Margin="14,41,12,61" AutoGenerateColumns="False"
HorizontalAlignment="Stretch" VerticalAlignment="Stretch"> ...
其他要點:
List
不是您的文章列表的非常好的屬性名稱 NotifyOfPropertyChange
提供了一個基於lambda的覆蓋,您應該使用它來捕獲重構 PropertyChanged
事件的消費者不再負責) 采用:
private List<Article> articles;
public List<Article> Articles
{
get
{
return this.articles;
}
private set
{
if (this.articles == value)
{
return;
}
this.articles = value;
this.NotifyOfPropertyChange(() => this.Articles);
}
}
由於這是一個集合類型,您還應該確保始終返回集合而不是null。 這可以防止消費者檢查以避免空引用異常。
這是Datagrid視圖的viewModel:
[Export(typeof(IScreen))]
public class BViewModel : Screen
{
private List<Article> articles;
public List<Article> Articles
{
get
{
return this.articles;
}
private set
{
if (this.articles == value)
{
return;
}
this.articles = value;
this.NotifyOfPropertyChange(() => this.Articles);
}
}
public BolleViewModel()
{
Articles = recoverArticles(); //returns a list of articles
}
public void Update(List<Article> list)
{
Articles = list;
}
//is associated with a button
public void Detail()
{
if(SelectedArticle!=null)
WindowManager.ShowWindow(new DetailArticleViewModel(SelectedArticle, Articles), null, null);
else
{
MessageBox.Show("Select an article","Error!",MessageBoxButton.OK,MessageBoxImage.Error);
}
}
}
DetailArticleViewModel更改文章列表項並調用BViewModel的Update方法。
[Export(typeof(IScreen))]
public class DetailArticleViewModel : Screen
{
public List<Article > GeneralList;
public Article ArticleSelected;
public BViewModel bw;
public DetailArticleViewModel(Article art,List<Article> arts,BViewModel viewmodel)
{
ArticleSelected = art;
GeneralList = arts;
bw = viewmodel;
}
// is associated with a button
public void Save()
{
var index = GeneralList.FindIndex(item => item.Code.CompareTo(ArticleSelected.Code)==0);
GeneralList[index].Price = 900;
bw.Update(List);
}
}
但所選文章的價格不是900! 為什么?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.