c# - 具有动态可编辑列的 DataGrid

标签 c# wpf mvvm dynamic datagrid

我一直在尝试在 WPF MVVM 项目中制作一个带有动态列的可编辑 DataGrid。动态列将是相同类型,即:decimal

目的是收集部门数量不确定的商店的部门总数。我试图在下面进行演示。

Day Dept1   Dept2   Dept3... TotalOfDepartments CashTotal CreditTotal
=====================================================================
1    100     200     50            350             50       300
2     75     100      0            175             25       150  

因此,有许多商店和不确定的部门,我的目标是收集月份

我想让 Department、CashTotal 和 CreditTotal 列可编辑。我试过几种方法,例如:

这是我对上一种方法的最后一次尝试。如下:

型号:

 public class DailyRevenues
    {
        public int ShopId { get; set; }
        public int Day { get; set; }
        public ObservableCollection<Department> DepartmentList { get; set; }

        public DailyRevenues()
        {
            this.DepartmentList = new ObservableCollection<Department>();
        }
    }

    public class Department
    {
        public string Name { get; set; }

        private decimal total;
        public decimal Total
        {
            get { return total; }
            set { total = value; }
        }
    }

View 模型:

public class DataItemViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public DataItemViewModel()
        {
            this.MonthlyRevenues = new ObservableCollection<DailyRevenues>();

            var d1 = new DailyRevenues() { ShopId = 1, Day = 1 };
            d1.DepartmentList.Add(new Department() { Name = "Deapartment1", Total = 100 });
            d1.DepartmentList.Add(new Department() { Name = "Deapartment2", Total = 200 });

            var d2 = new DailyRevenues() { ShopId = 1, Day = 2 };
            d2.DepartmentList.Add(new Department() { Name = "Deapartment1", Total = 75 });
            d2.DepartmentList.Add(new Department() { Name = "Deapartment2", Total = 150 });
            d2.DepartmentList.Add(new Department() { Name = "Deapartment3", Total = 100 });

            this.MonthlyRevenues.Add(d1);
            this.MonthlyRevenues.Add(d2);
        }

        private ObservableCollection<DailyRevenues> monthlyRevenues;
        public ObservableCollection<DailyRevenues> MonthlyRevenues
        {
            get { return monthlyRevenues; }
            set
            {
                if (monthlyRevenues != value)
                {
                    monthlyRevenues = value;
                    OnPropertyChanged(nameof(MonthlyRevenues));
                }
            }
        }

        private void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

和 XAML:

<DataGrid ItemsSource="{Binding MonthlyRevenues}" AutoGenerateColumns="False" >
        <DataGrid.Columns>
            <DataGridTextColumn Header="Day" Binding="{Binding Path=Day}" />
            <DataGridTextColumn Header="{Binding Path=MonthlyRevenues[0].DepartmentList[0].Name}" Binding="{Binding Path=DepartmentList[0].Total, Mode=TwoWay}" />
            <DataGridTextColumn Header="{Binding Path=DepartmentList[1].Name}" Binding="{Binding Path=DepartmentList[1].Total, Mode=TwoWay}" />
            <DataGridTextColumn Header="Department Total"/>
            <DataGridTextColumn Header="Cash Total" />
            <DataGridTextColumn Header="Credit Total" />
        </DataGrid.Columns>
    </DataGrid>

不幸的是,在最后一次尝试中,在 XAML 上使用索引器对动态列没有帮助,我找不到以任何其他方式绑定(bind)它们的方法。

更多信息:上面的数据网格(和数据演示)属于 shop1,我想在窗口/用户控件上收集其部门的月收入。每个店铺整个月都有相同的部门数,但这并不意味着每个部门每天都应该有收入,它可以为零。该部门可能会在任何一天关闭,因此当天不会增加任何收入。 Shop2 可能在同一个月有完全不同的部门,所以我不会在同一屏幕上处理所有商店。

编辑 1:添加了有关场景的更多信息。

最佳答案

您可以采用多种不同的方法,每种方法各有利弊。根据您对问题的更完整描述,我选择了自定义类型描述符方法。

在这里,我们将自定义类型描述符添加到每日收入类...

public class DailyRevenues : ICustomTypeDescriptor
{
    public int ShopId { get; set; }
    public int Day { get; set; }
    public ObservableCollection<Department> DepartmentList { get; set; }

    public DailyRevenues()
    {
        this.DepartmentList = new ObservableCollection<Department>();
    }
    public decimal TotalOfDepartments { get;  }
    public decimal CashTotal { get;  }
    public decimal CreditTotal { get; }

    public AttributeCollection GetAttributes()
    {
        return new AttributeCollection();
    }

    public string GetClassName()
    {
        return "DailyRevenues";
    }

    public string GetComponentName()
    {
        return "";
    }

    public TypeConverter GetConverter()
    {
        return null;
    }

    public EventDescriptor GetDefaultEvent()
    {
        return null;
    }

    public PropertyDescriptor GetDefaultProperty()
    {
        return null;
    }

    public object GetEditor(Type editorBaseType)
    {
        return null;
    }

    public EventDescriptorCollection GetEvents()
    {
        return null;
    }

    public EventDescriptorCollection GetEvents(Attribute[] attributes)
    {
        return null;
    }

    public PropertyDescriptorCollection GetProperties()
    {
        PropertyDescriptorCollection pdc0 = TypeDescriptor.GetProperties(typeof(DailyRevenues));
        List<PropertyDescriptor> pdList = new List<PropertyDescriptor>();
        pdList.Add(pdc0["Day"]);
        for (int i = 0; i < DepartmentList.Count; ++i)
        {
            pdList.Add(new DailyRevenuesProperty(DepartmentList[i].Name, i));
        }
        pdList.Add(pdc0["TotalOfDepartments"]);
        pdList.Add(pdc0["CashTotal"]);
        pdList.Add(pdc0["CreditTotal"]);
        return new PropertyDescriptorCollection(pdList.ToArray());
    }

    public PropertyDescriptorCollection GetProperties(Attribute[] attributes)
    {
        return GetProperties();
    }

    public object GetPropertyOwner(PropertyDescriptor pd)
    {
        return this;
    }
}

自定义类型描述符允许我们“扁平化”数据结构。随着部门数量的变化,对象的属性数量也会发生变化。这需要每日收入类别的自定义属性描述符...

public class DailyRevenuesProperty : PropertyDescriptor
{
    int _index;
    public DailyRevenuesProperty(string name, int index)
        : base(name, new Attribute[0])
    {
        _index = index;
    }
    public override Type ComponentType
    {
        get
        {
            return typeof(DailyRevenues);
        }
    }

    public override bool IsReadOnly
    {
        get
        {
            return false;
        }
    }

    public override Type PropertyType
    {
        get
        {
            return typeof(decimal);
        }
    }

    public override bool CanResetValue(object component)
    {
        return false;
    }

    public override object GetValue(object component)
    {
        DailyRevenues dr = component as DailyRevenues;
        if(dr != null && _index >= 0 && _index < dr.DepartmentList.Count)
        {
            return dr.DepartmentList[_index].Total;
        }
        else
        {
            return (decimal)0;
        }
    }

    public override void ResetValue(object component)
    {
    }

    public override void SetValue(object component, object value)
    {
        DailyRevenues dr = component as DailyRevenues;
        if (dr != null && _index >= 0 && _index < dr.DepartmentList.Count && value is decimal)
        {
            dr.DepartmentList[_index].Total = (decimal)value;
        }
    }

    public override bool ShouldSerializeValue(object component)
    {
        return false;
    }
}

现在我们需要一个类型列表。这取代了可观察的集合。

public class MonthlyRevenues : ObservableCollection<DailyRevenues>, ITypedList
{
    public PropertyDescriptorCollection GetItemProperties(PropertyDescriptor[] listAccessors)
    {
        if(Count > 0)
        {
            return TypeDescriptor.GetProperties(this[0]);
        }
        else
        {
            return TypeDescriptor.GetProperties(typeof(DailyRevenues));
        }
    }

    public string GetListName(PropertyDescriptor[] listAccessors)
    {
        return "Monthly Revenues";
    }
}

当自动生成列时,数据网格会检查项目集合是否为类型化列表。如果是,数据网格将查询类型化列表中的属性。

最后总结一下,这是数据网格...

    <DataGrid ItemsSource="{Binding MonthlyRevenues}" AutoGenerateColumns="true" />

这是生成的网格...

enter image description here

这种方法有很多限制。首先,我依靠数据网格来自动生成列。如果我想在标题文本中添加空格之类的东西,我需要做更多的事情。其次,我指望部门名称是有效的属性名称,并且不会与日常收入类别中的其他属性发生冲突。如果没有,那么我将需要做更多的事情。等等。

关于c# - 具有动态可编辑列的 DataGrid,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44958139/

相关文章:

c# - 如何在控制台应用程序中处理按键事件

.net - Silverlight 中的 DataTemplate.DataType 替代方案

wpf - 如果用户输入了无效的电子邮件地址,则禁用按钮 - WPF

c# - 将 ViewModel 传递给 UserControl

c# - C#正则表达式仅匹配字符串中完整单词的一部分

c# - 使用正则表达式验证密码 C#

c# - 从图片框保存图像,图像由图形对象绘制

c# - "System"警告颜色(红色)

c# - WPF窗口无法从Revit ExternalCommand初始化

c# - 使用 IDataErrorInfo 在 MVVM 中执行验证时,我应该在哪里执行检查以查看数据库中是否已存在值?