Wpf MVVM模型绑定初学者

Wpf MVVM模型绑定初学者,wpf,mvvm,data-binding,Wpf,Mvvm,Data Binding,我是MVVM和WPF的新手,我有点困惑 假设我有两个模型,如下所示: public class Category { public int Id { get; set; } public string Name { get; set; } } public class ProductViewModel : Screen { private Product _product; public BindableCollection<Category> Ca

我是MVVM和WPF的新手,我有点困惑

假设我有两个模型,如下所示:

public class Category
{
    public int Id { get; set; }
    public string Name { get; set; }
}
public class ProductViewModel : Screen
{
    private Product _product;
    public BindableCollection<Category> Categories;

    public ProductViewModel(Product product, BindableCollection<Category> categories)
    {
        _product = product;
        Categories = categories;
    }

    public Product Product
    {
        get { return _product }
        set
        {
            _product = value;
            SetAndNotify(ref _product, value);
        }
    }
}
<StackPanel Orientation="Vertical">
    <StackPanel Orientation="Horizontal">
        <Label Content="Catgory" />
        <ComboBox 
            ItemsSource="{Binding Categories}" 
            DisplayMemberPath="Name" 
            SelectedValue="?????? What comes here? "/>
    </StackPanel>
</StackPanel>

我不确定为添加新产品而推荐的实现
produceviewmodel
类的方法是什么:

只需使用
Product
类型的公共属性并将其绑定到视图即可,如下所示:

public class Category
{
    public int Id { get; set; }
    public string Name { get; set; }
}
public class ProductViewModel : Screen
{
    private Product _product;
    public BindableCollection<Category> Categories;

    public ProductViewModel(Product product, BindableCollection<Category> categories)
    {
        _product = product;
        Categories = categories;
    }

    public Product Product
    {
        get { return _product }
        set
        {
            _product = value;
            SetAndNotify(ref _product, value);
        }
    }
}
<StackPanel Orientation="Vertical">
    <StackPanel Orientation="Horizontal">
        <Label Content="Catgory" />
        <ComboBox 
            ItemsSource="{Binding Categories}" 
            DisplayMemberPath="Name" 
            SelectedValue="?????? What comes here? "/>
    </StackPanel>
</StackPanel>
这是正确的吗? 还有,我将如何在视图的
组合框中绑定
Product.Category


谢谢

在视图模型中,应该公开视图中需要的属性。在这种情况下,您可以直接绑定到Product.Category或在视图模型中创建新属性,我认为最后一个选项非常适合MVVM场景

在您的情况下,您应该为ProductViewModel创建一个选定的类别属性:

public Category SelectedCategory { get { return _selectedCategory; }
    set
    {
        _selectedCategory = value;
        SetAndNotify(ref _selectedCategory, value);
        Product.Category = _selectedCategory;
    } }
然后在xaml中,将combobox的选定值绑定到此新属性:

<StackPanel Orientation="Vertical">
<StackPanel Orientation="Horizontal">
    <Label Content="Catgory" />
    <ComboBox 
        ItemsSource="{Binding Categories}" 
        DisplayMemberPath="Name" 
        SelectedValue="{Binding SelectedCategory}"/>
</StackPanel>


您是否尝试了下面的解决方案?