c# - 如何使用多对多关系中的两个对象绑定(bind)到 WPF View ?

标签 c# wpf mvvm viewmodel observablecollection

鉴于我在我的数据访问层中有多对多关系(使用 CodeFirst - EF)例如

public class Report{
   public int ReportId {get;set;}
   public string ReportName {get;set;}
   public List<ReportKeyword> ReportKeywords {get;set;}
}

public class ReportKeyword{
   public int ReportId {get;set;}
   public int KeywordId {get;set;}
}

public class Keyword{
   public int KeywordId {get;set;}
   public string KeywordName {get;set;}
   public List<ReportKeyword> ReportKeywords {get;set;}
}

我需要创建一个显示报表 ListView 的用户界面(WPF View ),每个报表都应显示其关键字的子 ListView 。因此,这可以在 ViewModel 中轻松完成,但是为此目的建模 ViewModel 的最佳方式是什么。我是否需要创建具有必要属性的 VM?这是一个 ReportViewModel,它具有我想在报表对象之外显示的所有类似属性,包括一组关键字。

public class ReportViewModel : ViewModelBase<ReportViewModel>
{
    private string _reportName;
    public string ReportName
    {
        get { return _reportName; }
        set
        {
            _reportName = value;
            NotifyPropertyChanged(model => model.ReportName);
        }
    }
    private ObservableCollection<Keyword> _keywords;
    public ObservableCollection<Keyword> Keywords
    {
        get { return _keywords; }
        set
        {
            _keywords = value;
            NotifyPropertyChanged(model => model.Keywords);
        }
    }

}

我觉得有点乏味。如何填充集合以显示在网格上?是否应该在选择报告时调用设置关键字集合的方法?这种情况有更好的解决方案吗?

最佳答案

在我个人看来,你似乎已经差不多了。但是,我会为 View 模型提供一组 Report 对象,一个 Report 类型的属性绑定(bind)到 SelectedItem 属性集合控件,而不是您已有的 Keyword 对象的集合。

使用此 View 模型,我会将 Reports 属性绑定(bind)到 View 中的 ListBox.ItemsSource 并将 Report 属性绑定(bind)到 ListBox.ItemsSource 属性,以便用户可以选择各种报表对象。然后您可以简单地将所选 Report 对象的 ReportKeywords 属性绑定(bind)到 View 中的另一个 ListBox:

<ListBox ItemsSource="{Binding Reports/ReportKeywords}" />

这应该绑定(bind)到当前的 ReportKeywords 集合,或另一个 ListBox 中的选定项。

关于c# - 如何使用多对多关系中的两个对象绑定(bind)到 WPF View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18595566/

相关文章:

c# - 在 ViewModel 中更新 View

c# - 如何使用起订量来断言在 C# 中调用函数?

c# - 通过 MVVM 模式创建 UserControl - DataContext 并绑定(bind)到父级

silverlight - 根据属性值更改 VisualState

c# - 绑定(bind)不正确更新 usercontrol 属性 MVVM

c# - XAML 给出加载失败错误

wpf - 使用MVVM时如何将事件参数作为参数传递给interact.Trigger?

c# - 使用项目中包含的图像

c# - C#中将json文件反序列化为静态类

c# - 从 DbCommandDefinition 获取 CommandText