绑定DataGrid列标题

时间:2011-11-10 03:53:23

标签: .net wpf xaml mvvm .net-4.0

  

可能重复:
  Wpf Toolkit. Bind DataGrid Column Header to DynamicResource
  WPF Error: Cannot find govering FrameworkElement for target element

我正在使用MVVM模式创建一个WPF应用程序,所以在我的视图中,我试图将DataGrid列的列标题绑定到我的视图模型上的属性,该属性是视图的数据上下文DataGrid在。{/ p>

XAML:

<DataGrid Name="DailyData" AutoGenerateColumns="False" CanUserAddRows="False" CanUserDeleteRows="False" ItemsSource="{Binding Path=DailyDataViewModels}" HorizontalAlignment="Stretch">
                    <DataGrid.Columns>
                        <DataGridTextColumn Header="{Binding InflowVolumeLabel}" Binding="{Binding InflowVolume}"></DataGridTextColumn>
                    </DataGrid.Columns>
                </DataGrid>

但是标题只显示空白,似乎没有尝试绑定到指定的属性,如何绑定DataGrid列标题?

1 个答案:

答案 0 :(得分:1)

您遇到了DataGrid.Columns集合的问题,即它们不是同一个可视树的成员,因此只有Binding属性才有效。

我发现的唯一方法是将附加属性添加到DataGrid,这将在加载数据后应用标题。

public static readonly DependencyProperty ColumnHeadersProperty =
    DependencyProperty.RegisterAttached(
        "ColumnHeaders",
        typeof(IDictionary<string, string>),
        typeof(DataGrid),
        new UIPropertyMetadata(
            new Dictionary<string,string>(),
            ColumnHeadersPropertyChanged));

public static IDictionary<string,string> GetColumnHeaders(DependencyObject obj)
{
    return (IDictionary<string, string>)obj.GetValue(ColumnHeadersProperty);
}

public static void SetColumnHeaders(DependencyObject obj,
    IDictionary<string, string> value)
{
    obj.SetValue(ColumnHeadersProperty, value);
}

static void ColumnHeadersPropertyChanged(DependencyObject sender,
    DependencyPropertyChangedEventArgs e)
{
    var dataGrid = sender as DataGrid;
    if (dataGrid != null && e.NewValue != null)
    {
        dataGrid.AutoGeneratingColumn += AddColumnHeaders;
    }
}

static void AddColumnHeaders(object sender,
    DataGridAutoGeneratingColumnEventArgs e)
{
    var headers = GetColumnHeaders(sender as DataGrid);
    if (headers.ContainsKey(e.PropertyName))
    {
        e.Column.Header = headers[e.PropertyName];
    }
}

潜在的用途(可以改进):

// you could change it to use Column.DisplayIndex
this.dataGrid.SetValue(
    DataGridEx.ColumnHeadersProperty,
    new Dictionary<string, string>
    {
        { "PropertyName1", "Header 1" },
        { "PropertyName2", "Header 2" },
        { "PropertyName3", "Header 3" },
    });