如何从列表控件将项添加到视图模型可观察集合属性?WPF MVVM



这是我的第一个MVVM项目,我希望能说清楚。
在模型中有这个:

public class Category
{
public int CategoryId { get; set; }
public string Description { get; set; }
}

在视图中模型:

public class CategoryViewModel : MyViewModelBase
{
private ObservableCollection<Category> categories;
public ObservableCollection<Category> Categories
{
get { return categories; }
set
{
categories = value;
NotifyPropertyChanged(nameof(Categories));
}
}
}

在视图中 (XAML(
项绑定到组合框:

<ComboBox x:Name="cboCategories"
HorizontalAlignment="Left
VerticalAlignment="Top"
Width="250"
IsEditable="True"
ItemsSource="{Binding Categories}"
SelectedValuePath="CategoryId"
DisplayMemberPath="Description" />

当用户在控件上写入新条目时,有没有办法将新项(类别(添加到ObservableCollection属性?

我已经能够通过Window出现一个小TextBox来做到这一点,但我想知道是否有可能缩短这个过程。
我对 WPF 不是很熟悉,任何帮助将不胜感激。

假设您有一个类别集合,该集合绑定到组合的 itemssource。
然后,您将 selecteditem 绑定到带有 propfull 的 Category 类型的属性,以便您拥有可以放置代码的 setter。 当该二传手触发时,您将获得一个选定的类别。
然后你可以用它做你喜欢的事情。
一种选择是将其添加到另一个可观察集合中。

从列表中选择项目时的操作模式如下所述:
https://social.technet.microsoft.com/wiki/contents/articles/30564.wpf-uneventful-mvvm.aspx#Select_From_List_IndexChanged

在这种情况下,您可以将厨师添加到DoSomethingWhenChefChanged中的另一个可观察集合中。

您可以处理TextBoxBase.TextChanged附加事件,例如提出视图模型的命令或直接将项目添加到ObservableCollection中,例如:

private void cboCategories_TextChanged(object sender, TextChangedEventArgs e)
{
var cmb = sender as ComboBox;
var viewModel = DataContext as CategoryViewModel;
if (viewModel != null)
{
viewModel.Categories.Add(new Category() { Description = cmb.Text });
}
}

XAML:

<ComboBox x:Name="cboCategories"
IsEditable="True"
TextBoxBase.TextChanged="cboCategories_TextChanged" ... />

如果要使用交互触发器调用附加的命令,可以创建自己的自定义EventTrigger,如下所示:

http://joyfulwpf.blogspot.se/2009/05/mvvm-invoking-command-on-attached-event.html

https://social.msdn.microsoft.com/Forums/vstudio/en-US/c3e9fad4-16ee-4744-8b0e-1ea0abfc5da7/how-to-handle-scrollviewerscrollchanged-event-in-mvvm?forum=wpf

最新更新