如何解决双向绑定数据网格WPF XAML
public partial class TechnicalPropertiesU_Var : Window
{
public TechnicalPropertiesU_Var()
{
InitializeComponent();
List<Myclass> myclassList = new List<Myclass>();
myclassList.Add(new Myclass() { IA = 0,IB = 0,IC = 0,ID = 0,IE = 0,IF = 0,IF = 0 });
MyGrid.ItemsSource = myclassList;
}
}
MyWindow Xaml:
<Grid>
<DataGrid x:Name="MyGrid" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Argument Name"></DataGridTextColumn>
<DataGridTextColumn Header="Argument Value"></DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
模型类
public class Myclass
{
private int iA;
private int iB;
private int iC;
private int iD;
private int iE;
private int iF;
private int iG;
public int IA{get=>iA; set=>iA =value;}
public int IB{get=>iB; set=> iB =value;}
public int IC{get=>iC; set=> iC =value;}
public int ID{get=>iD; set=> iD =value;}
public int IE{get=>iE; set=> iE =value;}
public int IF{get=>iF; set=> iF =value;}
public int IG{get=>iG; set=> iG =value;}
}
如何在datagrid字段中获取特定的列。请给任何样品
解决方法
如果您尝试获得的结果是一个有两列的表(请参见您的图像),那么您显然会混淆行和列。数据类必须具有两个属性:ArgumentName
和ArgumentValue
。您必须知道每个项目(或MyClass
的每个实例)将显示为一行。现在,为每一行创建一个MyClass
的实例,并将其添加到源集合中。将DataGridTextColumn.Binding
属性绑定到MyClass
模型的列的相关属性。
以下示例将显示图片中的表格:
MyTableClass.cs
public class MyTableClass : INotifyPropertyChanged
{
public MyTableClass(int argumentName,int argumentValue)
{
this.ArgumentName = argumentName;
this.ArgumentValue = argumentValue;
}
private int argumentName;
private int argumentValue;
public int ArgumentName{get=>argumentName; set{argumentName=value; NotifyPropertyChanged();}}
public int ArgumentValue{get=>argumentValue; set{argumentValue=value; NotifyPropertyChanged();}}
public event PropertyChangedEventHandler PropertyChanged;
// This method is called by the Set accessor of each property.
// The CallerMemberName attribute that is applied to the optional propertyName
// parameter causes the property name of the caller to be substituted as an argument.
private void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this,new PropertyChangedEventArgs(propertyName));
}
}
}
技术属性U_Var.xaml.cs
public partial class TechnicalPropertiesU_Var : Window
{
public TechnicalPropertiesU_Var()
{
InitializeComponent();
List<MyTableClass> myTableClasses = new List<MyTableClass>();
myTableClasses.Add(new MyTableClass() { ArgumentName = "IA",ArgumentValue = 5 });
myTableClasses.Add(new MyTableClass() { ArgumentName = "IB",ArgumentValue = 3 });
myTableClasses.Add(new MyTableClass() { ArgumentName = "IC",ArgumentValue = 2 });
myTableClasses.Add(new MyTableClass() { ArgumentName = "ID",ArgumentValue = 0 });
MyGrid.ItemsSource = myTableClasses;
}
}
MyWindow.xaml
<Grid>
<DataGrid x:Name="MyGrid" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Argument Name" Binding="{Binding ArgumentName}"></DataGridTextColumn>
<DataGridTextColumn Header="Argument Value" Binding="{Binding ArgumentValue}"></DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
要发表您的评论: “我不想绑定参数名和参数值属性。我想绑定自己的CLR属性。因为我有250个变量。”
我不必了解您的意图就可以告诉您这是一个坏主意。一个类不应具有250个属性。您的图像清楚地表明,并非所有250个属性都具有关联,但是只有两个属性具有关联。
在您的情况下,数据由一个字符串值(例如"IA"
)和一个数字值(例如5
。您应该更改班级以反映这一点。
您应该知道,在常见的关系数据库设计中,数据记录由一行表示。每行是一个对象,此行的每一列都是该对象的属性。 DataGrid´ is designed with the same intention: each row is an item of the
DataGrid.ItemsSource`。每个项目都是一个单独的实例。通常从左到右读取任何表格,例如产品价格表,其中一行的每一列都应与单个数据项相关,例如产品。
我强烈建议您放弃最初的意图,并更改数据类以反映数据的关系,例如本示例的MyTableClass
反映具有两个属性(列)的数据对象(行)的关系。
您要执行的操作没有太大意义,尤其是从维护角度而言。您显然要列出250个变量。如果此列表被删减或扩展,现在您有2389个变量(夸大了,但仅此而已),该怎么办。您将要拔头发以保持头发。
相反,您应该了解有关类结构,更多可能的数据库的更多信息,并尝试找到一种通用模式。您拥有的每个“事物”都是基于整数的项目。但是每个“事物”都有相应的目的或描述,例如您的IA,IB,IC等。
我建议您考虑以下内容。我做了一个列举事情清单的调查员。下面的示例,但我只有IA-IG的产品。出于示例目的,我还给出了与其中两项相关的描述。
public enum my250Things
{
IA,IB,[Description("this is item C")]
IC,ID,IE,[Description("testing F description")]
IF,IG
}
因此,现在在您的代码中,如果我有一个基于“ my250Things”类型的变量,则可以通过其枚举引用它来知道它代表什么。
返回您的数据网格。由于您要呈现的所有记录都是一行,并且显示了相应的变量名上下文(IA,IB等)及其包含的值,因此我创建了一个类。此类实际上具有3个属性。一个show值,一个show int以及基于它创建的原始枚举值。在下面。
public class YourCommonThings : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string _yourShowValue;
public string YourShowValue
{
get { return _yourShowValue; }
set { _yourShowValue = value;
NotifyPropertyChanged(); }
}
private int _yourIntValue;
public int YourIntValue
{
get { return _yourIntValue; }
set
{
_yourIntValue = value;
NotifyPropertyChanged();
}
}
private my250Things _theOriginalEnum;
public my250Things TheOriginalEnum
{
get { return _theOriginalEnum; }
set
{
_theOriginalEnum = value;
NotifyPropertyChanged();
}
}
// This method is called by the Set accessor of each property.
// The CallerMemberName attribute that is applied to the optional propertyName
// parameter causes the property name of the caller to be substituted as an argument.
private void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this,new PropertyChangedEventArgs(propertyName));
}
}
现在,我想填充要显示给用户的内容列表。由于枚举让我知道了我要跟踪的“事物”,因此我可以使用它来填充列表以及它的描述(如果适用)。如果没有,则默认使用枚举本身的字符串表示形式。我为演示创建了一个简单的窗口“ Stack1”,创建了一个公共属性,用于将数据列表绑定到该列表并根据枚举自动填充。
您将需要在窗口.cs文件顶部的这些“使用”引用
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Windows;
这是窗口代码背后的代码
public partial class Stack1 : Window
{
// first,making a public property as a list of the things I want to present
public List<YourCommonThings> BindToThisListOfThings { get; set; }
// the name of my window is called "Stack1" and this is the constructor of the window
public Stack1()
{
// start by declaring a new list of things based on the class
BindToThisListOfThings = new List<YourCommonThings>();
// Now,we can dynamically create a list of all the "things" you are trying to present
// into your data grid. In this case,I am going through an enumerator list,but could
// also be done if the list of things was stored in a database (for example) and you
// queried from that,but that is a different question / option.
foreach(my250Things oneThing in typeof( my250Things ).GetEnumValues() )
{
// creating one instance of whatever your enum underlying thing is and
// default setting the properties within the class instance for the parts
// that are within the { }
// the ".ToString()" portion will get your "IA","IB",...
// I can also add in to store the original enum value while I'm at it,// even though not showing to the end user in the screen.
var justOne = new YourCommonThings
{ YourShowValue = oneThing.ToString(),YourIntValue = 0,TheOriginalEnum = oneThing };
// and you can optionally just for sake of example purposes associate a description
// to an enum value and pull THAT instead...
string description = GetEnumDescription(oneThing);
if (!string.IsNullOrWhiteSpace(description))
justOne.YourShowValue = description;
// Now,add to your list
BindToThisListOfThings.Add(justOne);
}
// Now,you have your list prepared and ready to go for binding to
DataContext = this;
// and finish initializing the rest of the form.
InitializeComponent();
}
// this static method is used to get the "description" component
// out of the enumeration declaration IF such a description is declared.
public static string GetEnumDescription(Enum value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes = fi.GetCustomAttributes(typeof(DescriptionAttribute),false) as DescriptionAttribute[];
if (attributes != null && attributes.Any())
return attributes.First().Description;
return value.ToString();
}
}
最后,在表单的xaml中,我将数据网格绑定到从枚举中准备的事物列表。
<DataGrid AutoGenerateColumns="False" VerticalContentAlignment="Stretch"
ItemsSource="{Binding BindToThisListOfThings,NotifyOnSourceUpdated=True}">
<DataGrid.Columns>
<DataGridTextColumn Header="Argument Name" Binding="{Binding YourShowValue}" Width="125" />
<DataGridTextColumn Header="Argument Value" Binding="{Binding YourIntValue}" Width="125" />
</DataGrid.Columns>
</DataGrid>
现在,在表单/窗口中,或者在定义了MVVM模式的任何位置(此时是疑问),但是无论如何,无论您打算保存数据,您都可以循环浏览事物列表,并获取它们各自的信息内容和说明可保存在您计划的任何地方,但您的问题中并未披露该内容和说明以进一步应用。
public void SaveData()
{
foreach( var oneThing in BindToThisListOfThings )
{
// Here,you can refer to
// oneThing.YourShowValue
// oneThing.YourIntValue
// oneThing.TheOriginalEnum
}
}
祝你好运。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。