.net - 绑定(bind) DataGrid 列标题

标签 .net wpf xaml mvvm .net-4.0

这个问题在这里已经有了答案:




10年前关闭。




Possible Duplicate:
Wpf Toolkit. Bind DataGrid Column Header to DynamicResource
WPF Error: Cannot find govering FrameworkElement for target element



我正在使用 MVVM 模式创建一个 WPF 应用程序,所以在我看来,我正在尝试绑定(bind) DataGrid 的列标题我的 View 模型上的属性列,它是 DataGrid 的 View 的数据上下文。在。

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>

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

最佳答案

您在 DataGrid.Columns 上遇到了一个巧妙的问题。集合,即它们不是同一可视树的成员,因此只有 Binding属性(property)似乎工作。

我发现唯一可行的方法是将附加属性添加到 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" },
    });

关于.net - 绑定(bind) DataGrid 列标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8074810/

相关文章:

wpf - 模板 XAML 中的 GroupBox 可见性

c# - MVVM 解决方案结构

c# - .NET 图像是全黑的吗?

.net - 动态添加客户端脚本/HTML 调用服务器端事件

wpf - 如何获取 WPF ItemsControl 的通用 ItemContainer 类型

c# - 从不同线程更新主窗口中的进度条

c# - 绑定(bind) ComboBox ItemsSource 在 WPF 中不起作用

c# - ASP.NET MVC 2 应用程序中类似 Twitter 的路由

.net - WAT080 : Failed to locate the Microsoft Azure SDK 有解决方法吗

c# - XAML 内联数据绑定(bind)不起作用;绑定(bind)作品背后的代码