我使用Prism。数据提供程序正常工作(这里是SQLite)。
<ListBox ItemsSource="{Binding Path=CategoryList}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Name}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
public class ListsViewModel : BindableBase
{
private readonly IDataProvider _dataProvider;
private readonly IRegionManager _regionManager;
public DelegateCommand ClickAddCategory { get; set; }
private string categoryName;
public string CategoryName
{
get { return categoryName; }
set { SetProperty(ref categoryName, value); }
}
private ObservableCollection<ExtraCategory> categoryList;
public ObservableCollection<ExtraCategory> CategoryList
{
get
{
if (categoryList == null) return _dataProvider.GetCategoryList();
else return categoryList;
}
set { SetProperty(ref categoryList, value); }
}
public ListsViewModel(IRegionManager regionManager, IDataProvider dataProvider)
{
_dataProvider = dataProvider;
_regionManager = regionManager;
ClickAddCategory = new DelegateCommand(ClickedAddCategory);
//MessageBox.Show("Hello from " + this.ToString());
}
private void ClickedAddCategory()
{
ExtraCategory newCategoryFromForm = new ExtraCategory(CategoryName);
CategoryList.Add(newCategoryFromForm);
_dataProvider.AddCategory(newCategoryFromForm);
}
}
如果我改变行:
CategoryList.Add(newCategoryFromForm);
CategoryList = _dataProvider.GetCategoryList();
一切都可以正常工作,因为set{}内的代码将运行,但这不是一个解决方案。我真的很感激你的帮助。而且我真的不想打破MVVM模式。
您想要将ObservableCollection
放在没有setter的属性中。而你希望这个值保持不变。
private ObservableCollection<ExtraCategory> categoryList;
public ObservableCollection<ExtraCategory> CategoryList
{
get
{
if (categoryList == null) return _dataProvider.GetCategoryList();
else return categoryList;
}
set { SetProperty(ref categoryList, value); }
}
这给你一个新的ObservableCollection
每次你调用CategoryList.get
,即CategoryList.Add(newCategoryFromForm);
获取一个新的列表,添加新的项目,然后丢弃列表(从属性的getter返回一个值不会神奇地设置一个支持字段)。
我会这样做:
public ObservableCollection<ExtraCategory> CategoryList { get; }
和构造函数中:
CategoryList = _dataProvider.GetCategoryList();
使用并安装nuget包PropertyChange.Fody.
你的类看起来像这样:
public class ListsViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private readonly IDataProvider _dataProvider;
private readonly IRegionManager _regionManager;
public DelegateCommand ClickAddCategory { get; set; }
public string CategoryName { get; set; }
public ObservableCollection<ExtraCategory> CategoryList { get; set; }
public ListsViewModel(IRegionManager regionManager, IDataProvider dataProvider)
{
_dataProvider = dataProvider;
_regionManager = regionManager;
ClickAddCategory = new DelegateCommand(ClickedAddCategory);
CategoryList = _dataProvider.GetCategoryList();
//MessageBox.Show("Hello from " + this.ToString());
}
private void ClickedAddCategory()
{
ExtraCategory newCategoryFromForm = new ExtraCategory(CategoryName);
CategoryList.Add(newCategoryFromForm);
_dataProvider.AddCategory(newCategoryFromForm);
}
}
我相信它会完美地工作
如果你想更新列表,使用一个方法并绑定一个命令,当你想刷新
时执行