1.XAML源代码
<UserControl x:Class="DgridHeaderBinding.MainPage" 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" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="400" xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data" xmlns:dataprimitives="clr-namespace:System.Windows.Controls.Primitives;assembly=System.Windows.Controls.Data" xmlns:sys="clr-namespace:System;assembly=mscorlib" xmlns:local="clr-namespace:DgridHeaderBinding" > <UserControl.Resources> <local:People x:Key="folks"/> <local:BindingConverter x:Key="BindCon"/> <Style x:Key="ColBinding" TargetType="dataprimitives:DataGridColumnHeader" > <Setter Property="ContentTemplate" > <Setter.Value> <DataTemplate> <ContentPresenter Content="{Binding Converter={StaticResource BindCon}}" /> </DataTemplate> </Setter.Value> </Setter> </Style> </UserControl.Resources> <Grid x:Name="LayoutRoot" Background="White"> <StackPanel> <TextBox Text="binding header" x:Name="tbox" /> <data:DataGrid ItemsSource="{Binding AllPeople,Source={StaticResource folks}}" AutoGenerateColumns="False" ColumnHeaderStyle="{StaticResource ColBinding}" > <data:DataGrid.Columns> <data:DataGridTextColumn Binding="{Binding ID}" Header="{Binding Text, ElementName=tbox}" /> <data:DataGridTextColumn Binding="{Binding Name}" Header="hello" /> </data:DataGrid.Columns> </data:DataGrid> </StackPanel> </Grid> </UserControl>
2.CS代码
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Controls; using System.Windows.Data; using System.Globalization; namespace DgridHeaderBinding { public partial class MainPage : UserControl { public MainPage() { InitializeComponent(); } } public class Person { public int ID { get; set; } public string Name { get; set; } } public class People { public People() { AllPeople = (from a in Enumerable.Range(1, 100) select new Person { ID = a, Name = "Name: " + a } ).ToList(); } public List<Person> AllPeople { get; set; } } public class BindingConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value.GetType().Name == "Binding") { ContentControl cc = new ContentControl(); cc.SetBinding(ContentControl.ContentProperty, value as Binding); return cc; } else return value; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return null; } } }
效果图
源代码:http://download.csdn.net/detail/mh942408056/8730943
时间: 2024-10-12 17:04:54