将 WPF 数据网格与数据表及其父类绑定

问题描述 投票:0回答:1

我有一个包含数据表的类。我想绑定一个包含六列的 WPF 数据网格,其中前四列将与父类的属性绑定,最后两列将被绑定 其中包含数据表列中的值。

数据网格中的前四列非常简单。我对绑定数据表中的值感到困惑。

会有点像这样

   //Code Behind

public class ParentClass()

{

public string PropertyOne { get; set; }
public string PropertyTwo { get; set; }
public string PropertyThree { get; set; }
public string PropertyFour { get; set; }    
public DataTable Data { get; set; }

public class()
{
    Data.columns.add("ColumnOne");
    Data.columns.add("ColumnTwo");
    
    DataRow objRow = Data.newRow();
    objRow["ColumnOne"] = "ColumnOne";
    objRow["ColumnTwo"] = "ColumnTwo";
    
    Data.Rows.add(objRow);
}

XAML代码来了

//XAML


<DataGrid.Columns>
                <DataGridTextColumn Header="First" Width="150" Binding="{Binding PropertyOne}"></DataGridTextColumn>
                <DataGridTextColumn Header="Second" Width="150" Binding="{Binding PropertyTwo}"></DataGridTextColumn>
                <DataGridTextColumn Header="Third" Width="150" Binding="{Binding PropertyThree}"></DataGridTextColumn>
                <DataGridTextColumn Header="Fourth" Width="150" Binding="{Binding PropertyFour}"></DataGridTextColumn>
                <DataGridTextColumn Header="Fifth" Width="150" Binding="{Binding ColumnOne}"></DataGridTextColumn>
                <DataGridTemplateColumn Header="Sixth" Width="150">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <TextBlock Name="txtTest" text="{Binding ColumnTwo}"></TextBlock>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>

 

c# wpf data-binding datagrid
1个回答
0
投票

只需再添加两个属性并将值分配给它们并绑定它们

public class ParentClass()
{
   public string PropertyOne { get; set; } 
   public string PropertyTwo { get; set; }
   public string PropertyThree { get; set; }
   public string PropertyFour { get; set; }     
   public string ColumnOne { get; set; }
   public string ColumnTwo{ get; set; }
}

public class OtherClass()
{
     Data.columns.add("ColumnOne");
     Data.columns.add("ColumnTwo");

    DataRow objRow = Data.newRow();
    objRow["PropertyOne"] = parentClass.PropertyOne;
    ...
    objRow["PropertyFour "] = parentClass.PropertyFour ;
    objRow["ColumnOne"] = "ColumnOne";
    objRow["ColumnTwo"] = "ColumnTwo";

    Data.Rows.add(objRow);
    
}
//bind the Data to the grid

public class OtherClass()
{
  //Read data from the database and assign them to the instance of the parent class and add them to the list you want to bind. 
   var parentClass = new ParentClass();
   //assign properties.
   //read the row from the database
   //assign the properties from the database.
   //add them to the list to bind 
   
}

你想要达到的目标是可行的,但完全不推荐。使用两种方式中的任何一种。

© www.soinside.com 2019 - 2024. All rights reserved.