数据网格与动态可编辑列

4
我一直在尝试在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; }
        }
    }

视图模型:

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的索引器进行尝试时,我发现它不能帮助我处理动态列,并且我找不到其他绑定方式。
更多信息:上面的数据网格(和数据演示)属于shop1,我想在一个窗口/用户控件中收集其部门的月收入。每个商店在整个月份内都有相同数量的部门,但这并不意味着每个部门每天都应该有收入,可能为零。该部门可能在任何一天关闭,因此当天没有产生任何收入。对于同一月份,Shop2可能拥有完全不同的部门,因此我将不会在同一屏幕上处理所有商店。
编辑1:添加了关于情景的更多信息。

你有没有看过/考虑过绑定 DataTable?例如:https://stackoverflow.com/a/44206066/1506454 - ASh
@ASh,我该如何让它双向操作。我的意思是编辑没问题,但我要如何获取ViewModel上的数据,在那里执行一些魔法? - G.Anıl Yalçın
1
应该是双向的?使用 DataTable 绑定后,单击 DataGrid 单元格应允许编辑值。更改将反映在 DataTable 单元格中。 - ASh
DataTable绑定DataGrid单元格点击事件,使用mvvm模式?我会研究一下。 - G.Anıl Yalçın
1
DataTable无法帮助您处理可变数量的列。您正在要求行/列结构做很多事情。有一种方法可以实现您的要求,但我需要确切地了解您正在做什么。在您的示例中,第1天商店1有2个部门。第2天它有3个部门,其中2个与第1天相同。如果第2天所有名称都不同怎么办?那么是否有5列?如果商店2有相同名称的部门,它们是同一列吗?等等。 - AQuirky
1个回答

3

有几种不同的方法可以采取,每种方法都有其优缺点。根据您对问题的更完整描述,我选择了自定义类型描述符方法。

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

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

这种方法存在一些限制。首先,我依赖于数据网格自动生成列。如果我想在标题文本中添加空格之类的东西,我需要做更多的工作。其次,我指望部门名称是有效的属性名称,并且不会与每日收入类中的其他属性冲突。如果不是这样,我需要做更多的工作。等等。


感谢您的帮助。我已经研究了您的方法,但我似乎仍然无法正确地解释我的问题。根据您的更改,我已经在视图模型中声明了一个MonthlyRevenues属性,而不是ObservableCollection。我知道DailyRevenues:ICustomTypeDescriptor类的属性的数据网格可编辑性取决于setter。DepartmentList有一个setter,但结果网格上的第1和第2个部门列不可编辑。我需要另一个“类型化列表”或另一个“自定义类型描述符”吗? - G.Anıl Yalçın
1
不,这很容易解决。我没有意识到您想要编辑部门总数,因为它上面没有设置器。我已经编辑了答案,所以现在您可以编辑部门总数了。除了将设置器添加到部门总数之外,更改的内容是属性描述符:(1)将IsReadOnly更改为false,(2)实现SetValue函数。 - AQuirky
这看起来很有前途。但还有一些我弄不清楚的地方。我该如何在 Department Total 变化时触发 propertyChanged,比如将 Department1 从100改为200,以便重新计算 TotalOfDepartments? - G.Anıl Yalçın
1
非常简单。在Department上实现INotifyPropertyChanged接口,并监听DailyRevenues的Total属性的更改。 - AQuirky
谢谢,AQuirky。虽然花了一些时间,但是你的回答帮我找到了解决方案。我会编辑问题并尽快发布我的方法。 - G.Anıl Yalçın

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接