双向绑定数据网格WPF XAML

如何解决双向绑定数据网格WPF XAML

我想将CLR属性绑定到datagrid行中如何在datagrid中绑定行绑定(双向模式)

enter image description here

CodeBehind:

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字段中获取特定的列。请给任何样品

解决方法

如果您尝试获得的结果是一个有两列的表(请参见您的图像),那么您显然会混淆行和列。数据类必须具有两个属性:ArgumentNameArgumentValue。您必须知道每个项目(或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 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-