之前写过的一遍文章,在这里直接贴出来。
场景:根据配置文件显示DataGrid中的某些列。
问题:Columns集合只是DataGrid的一个属性,这个集合在逻辑树或视觉树中是看不到的,也不会继承DataContext属性。
通过网上查阅各种资料,方法可以归结以下几种,下面将一一展示。
方法一:对DataGridColumn附加DataContext属性
该方法需要用到一个帮助类(需要创建一个全局实例),具体内容如下:
public class DataGridContextHelper
{
static DataGridContextHelper()
{
DependencyProperty dp = FrameworkElement.DataContextProperty.AddOwner(typeof(DataGridColumn));
FrameworkElement.DataContextProperty.OverrideMetadata(typeof(DataGrid),
new FrameworkPropertyMetadata
(null, FrameworkPropertyMetadataOptions.Inherits,
new PropertyChangedCallback(OnDataContextChanged)));
}
public static void OnDataContextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
DataGrid grid = d as DataGrid;
if (grid != null)
{
foreach (DataGridColumn col in grid.Columns)
{
col.SetValue(FrameworkElement.DataContextProperty, e.NewValue);
}
}
}
}
前台绑定示例
<DataGridTextColumn x:Name="col2" Header=