c# - 如何在 WPF DataGrid/ListView/ListBox 中添加计算的附加列

标签 c# .net wpf data-binding

我有一个 DataGrid 和一个 View 模型 (MyViewModel1)。 DataGrid 绑定(bind)到 MyViewModel1 的 Items 属性。约束是我不能触及 MyViewModel1MyClass1 的代码。

public class MyViewModel1 : INotifyPropertyChanged
{
    ...
    public ObservableCollection<MyClass1> Items { get { ... } }
    public int ViewModelProperty1 { get { ... } }
    public int ViewModelProperty2 { get { ... } }
}

public class MyClass1 : INotifyPropertyChanged
{
    ...
    public int Property1 { get { ... } }
    public int Property2 { get { ... } }
    public int Property3 { get { ... } }
}

我希望 DataGrid 不仅显示具有 3 个已知属性的 3 列,而且每行还显示第 4 列,这取决于 Property1Property2Property3ViewModelProperty1ViewModelProperty2。为了示例,假设第 4 列是 Property1 + Property2 + Property3 + ViewModelProperty1 + ViewModelProperty2。第 4 列必须显示当前值,因此如果 ViewModelProperty1 增加 1,则第 4 列也必须增加 1。我的问题是:我有什么选择可以做到这一点?

我能想到这些:

  1. 使用 IMultiValueConverter 将所有因变量作为输入。这适用于示例。这里的问题是,一旦变量的相互作用变得更加复杂,例如((Property1 + 2*Property2) * Property3) ^ (ViewModelProperty1 - ViewModelProperty2),'MultiBinding'中5个变量的顺序变得很重要,其中有很多知识结合会导致溶液变脆。

  2. 使用包装器。将 DataGrid 绑定(bind)到一个新类 MyViewModel2,它注册到 MyViewModel1 上的更改,看起来像

    public class MyViewModel2
    {
        public MyViewModel2(MyViewModel1 m) { ... }
        ...
        public ObservableCollection<MyClass2> Items { get { ... } }
    }
    public class MyClass2 : INotifyPropertyChanged
    {
        public MyClass2(MyClass1 inner)
        {
            InnerClass = inner;
            InnerClass.NotifyPropertyChanged += InnerClassChanged;
        }
        void InnerClassChanged(object o, PropertyChangedEventArgs)
        {
            if (PropertyChanged != null)
                PropertyChanged("Property4");
        }
        public void ViewModelPropertiesChanged
        {
            if (PropertyChanged != null)
                PropertyChanged("Property4");
        }
    
        public MyClass1 InnerClass { get; private set; }
        public int Property4
        {
            get { return InnerClass.Property1+InnerClass.Property2 ... }
        }
        public event PropertyChanged;
    }
    

问题是除了我上面提到的 2 个(Converter 和 Wrapper)之外,还有什么方法可以解决这个问题。

我的问题不是哪种方法是解决该示例的最佳方法。

最佳答案

不好意思,刚看到你已经想到了!并不是说我理解你的反对意见。

你可以使用 MultiBindingIMultiValueConverter .请参阅 IMultiValueConverter 文档中的示例。

(从这里开始:https://stackoverflow.com/a/2002598/360211)

关于c# - 如何在 WPF DataGrid/ListView/ListBox 中添加计算的附加列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13827716/

相关文章:

c# - Linq to XML 与 DOM

c# - 使用 LINQ 和 Entity Framework 检查 c# var 中的空值

c# - 从 FTP 上传文件和下载文件

c# - SSIS 2012 : is it possible to pass references to Package Objects to an external assembly?

c# - dll 的 app.config 中的连接字符串

.net - 存储过程在 Entity Framework 中很慢

.net - ViewModel 内模型的 MVC DropDown

wpf - 如何使 WPF DataGrid 单元格右对齐而不使新行上的可选区域变小?

wpf - MVVM - 如何将 View 模型绑定(bind)到 View

c# - 自定义绘制控件的糟糕表现