DataGrid实现Header与数据的绑定

一.xaml代码:

       注意:列的数据可以绑定,但Hearder的绑定要使用HearderTemplate中的TextBlock元素来实现,切记。

复制代码
<Window x:Class="AirtightTest.TestView"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:AirtightTest"
        mc:Ignorable="d"
        Title="TestView" Height="450" Width="800">
    <Grid>
        <DataGrid x:Name="dgrid1" >
            <DataGrid.Columns>
                <DataGridTextColumn Binding="{Binding Value1}">
                    <DataGridTextColumn.HeaderTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding DataContext.ColunmTitle1, RelativeSource={RelativeSource AncestorType={x:Type local:TestView}}}"/>
                        </DataTemplate>
                    </DataGridTextColumn.HeaderTemplate>
                </DataGridTextColumn>

                <DataGridTextColumn Binding="{Binding Value2}">
                    <DataGridTextColumn.HeaderTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding DataContext.ColunmTitle2, RelativeSource={RelativeSource AncestorType={x:Type local:TestView}}}"/>
                        </DataTemplate>
                    </DataGridTextColumn.HeaderTemplate>
                </DataGridTextColumn>

            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>
复制代码

二.定义两个实体类

复制代码
// 对应表头名称的实体类
public
class MyTitle { public string ColunmTitle1 { get; set; } public string ColunmTitle2 { get; set; } }
// 对应表列的数据实体类
public class MyValue { public int Value1 { get; set; } public double Value2 { get; set; } }
复制代码

三.实例化对象并设置绑定上下文

复制代码
// 窗体类
public
partial class TestView : Window {
    // 窗体的构造中,实体化实体类并设置绑定
public TestView() { InitializeComponent(); MyTitle my = new MyTitle { ColunmTitle1 = "Title1", ColunmTitle2 = "Title2", }; DataContext = my; List<MyValue> value = new List<MyValue> { new MyValue { Value1 = 1, Value2 = 2.3 }, new MyValue { Value1 = 2, Value2 = 3.3 }, }; this.dgrid1.ItemsSource = value; } }
复制代码

 

posted @   獨懼  阅读(320)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示