我有带有组合框和按钮的WPF应用程序。在将值输入文本框并按按钮之后,来自文本框的值应出现在组合框的更新列表中。我正在尝试使用MVVM并绑定到combobox。这是ViewModel代码的一部分。
public class ViewModel:INotifyPropertyChanged
{
DomainLogic dl = new DomainLogic();
public event PropertyChangedEventHandler PropertyChanged;
private ObservableCollection<string> expenseCategories = new ObservableCollection<string>();
public ObservableCollection<string> ExpenseCategories
{
get
{
return expenseCategories;
}
set
{
expenseCategories = value;
OnPropertyChanged("ExpenseCategories");
}
}
public ViewModel()
{
expenseCategories = new ObservableCollection<string>(dl.GetExpenseCategories());
}
private void OnPropertyChanged(string property)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
我还使用EF来访问数据库,并且DomainLogic类具有列出所有费用类别的方法。
这是从窗口隐藏的代码:
DomainLogic dl = new DomainLogic();
public Window1()
{
InitializeComponent();
DataContext = new ViewModel();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
if (!string.IsNullOrWhiteSpace(textBox.Text))
{
dl.CreateNewExpenseCategory(textBox.Text);
}
else
{
MessageBox.Show("Enter category!");
}
}
这里也是XAML:
<ComboBox x:Name="ExpCategory" HorizontalAlignment="Left" Margin="72,50,0,0" VerticalAlignment="Top" Width="130" ItemsSource="{Binding ExpenseCategories, UpdateSourceTrigger=PropertyChanged}" />
当我添加新类别时,组合框不会更新。我是整个MVVM模式的新手,我想这里缺少一些东西。
//编辑
public void CreateNewExpenseCategory(string name)
{
using (var context = new ExpenseEntities())
{
ExpenseCategory category = new ExpenseCategory() { CategoryName = name};
context.ExpenseCategory.Add(category);
context.SaveChanges();
}
}
答案 0 :(得分:2)
问题在于CollectionChanged
事件不会触发。
您要在DataContext中添加一个新元素,但不会更新本地数据视图。
一旦更新了DataContext,您应该刷新ObservableCollection
或使用Local。
这里是Local
的使用方式:
public ViewModel()
{
expenseCategories = dl.GetExpenseCategories().Local;
}
因此您可以直接这样做:
expenseCategories.Add(new ExpenseCategory() {textBox.Text});
dl.GetContext().SaveChanges();
或者您必须更新ObservableCollection
:
dl.CreateNewExpenseCategory(textBox.Text);
// Update your ViewModel ObservableCollection.
但是我认为您应该使用Command
而不是事件,以便可以直接在ViewModel内部更新ObservableCollection
。
示例:
using Prism.Commands;
//Other usings
public class ViewModel : INotifyPropertyChanged
{
// Your class methods and properties
public DelegateCommand<string> AddNewExpenseCategory
{
get
{
return new DelegateCommand<string>(Execute_AddNewExpenseCategory);
}
}
public void Execute_AddNewExpenseCategory(string param)
{
expenseCategories.Add(new ExpenseCategory() { param });
dl.GetContext().SaveChanges();
}