gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 18:32:32 25 4
gpt4 key购买 nike

鉴于我在我的数据访问层中有多对多关系(使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com