以编程方式设置 wpf datagrid 单元格值 [英] Set wpf datagrid cell value programmatically

查看:47
本文介绍了以编程方式设置 wpf datagrid 单元格值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的数据网格,包含 2 列,ProductCode 和 Description.
当用户在第一列中编译 ProductCode 并移至下一列时,程序应使用 Products 表中的产品描述编译 Description 单元格.
这样做的最佳方法是什么?

I have a simple datagrid with 2 columns, ProductCode and Description.
When user compile a ProductCode in the first column and move to the next column, the program should compile the Description cell with the description of the product found in the Products table.
What is the best approach to do this?

推荐答案

这样做的最佳方法是什么?

What is the best approach to do this?

定义一个具有两个属性的类,ProductCodeDescription,用于实现 INotifyPropertyChanged 接口.然后,您可以在 ProductCode 属性的 setter 中查找产品的描述,例如:

Define a class with two properties, ProductCode and Description, that implements the INotifyPropertyChanged interface. You can then lookup the description of the products in the setter of the ProductCode property, e.g.:

public class Product : INotifyPropertyChanged
{
    private string _productCode;
    public string ProductCode
    {
        get { return _productCode; }
        set
        {
            _productCode = value;
            NotifyPropertyChanged();
            LookupProduct();
        }
    }

    private string _description;
    public string Description
    {
        get { return _description; }
        set { _description = value; NotifyPropertyChanged(); }
    }

    private void LookupProduct()
    {
        //loop up product based on _productCode here
        //...and set the Description property:
        Description = "...";
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

您当然也应该将 DataGridItemsSource 属性设置或绑定到 IEnumerable.

You should of course also set or bind the ItemsSource property of the DataGrid to an IEnumerable<Product>.

这篇关于以编程方式设置 wpf datagrid 单元格值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆