1

我有一个 Itemsource 并从中绑定数据网格中的值

    <DataGridTextColumn Header="Message" Binding="{Binding Path=message}"/>
    <DataGridTextColumn Header=" Logger" Binding="{Binding Path=logger}"/>
    <DataGridTextColumn Header="Level" Binding="{Binding Path=level}" />

我还必须将标题文本与键字典绑定

    Dictionary<String, object>.KeyCollection keyslist = dict1.Keys;

使用这本字典,我必须绑定标题文本。

是否可以为 Datagrid 提供两个 itemsource ?

4

1 回答 1

0

对您的问题的简短回答是:是的,有可能。虽然这是一种混乱的做事方式,我不建议这样做(除非你真的必须这样做,因为我不知道你的上下文细节),但这里的想法是:

  1. 第一个问题是,Header 绑定似乎有些损坏。我无法通过常规方式绑定到它,除非通过 Source={x:Static} 定义备用数据上下文。

  2. 在 Header 绑定中无法绑定到集合,因此您需要给它一个缩放器值或编写一个转换器,该转换器接受一个参数并在您的字典中查找它以返回实际值。

下面是示例代码,展示了我们如何测试绑定(没有转换器):

XAML

<Window x:Name="window" x:Class="WpfDataGridMisc.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="214" DataContext="{Binding Source={x:Static wpfDataGridMisc:PersonsViewModel.Instance}}"
        xmlns:wpfDataGridMisc="clr-namespace:WpfDataGridMisc">
    <DataGrid AutoGenerateColumns="False" ItemsSource="{Binding Persons}">
        <DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding FirstName}" Header="{Binding Source={x:Static wpfDataGridMisc:PersonsViewModel.Instance}, Path=Header1}" />
        </DataGrid.Columns>
    </DataGrid>
</Window>

人员视图模型

using System;
using System.Collections.ObjectModel;

namespace WpfDataGridMisc
{
    public class PersonsViewModel
    {
        private static readonly PersonsViewModel Current = new PersonsViewModel();

        public static PersonsViewModel Instance { get { return Current; } }

        private PersonsViewModel()
        {
            Persons = new ObservableCollection<Person>
                {
                    new Person {FirstName = "Thomas", LastName = "Newman", Date = DateTime.Now},
                    new Person {FirstName = "Dave", LastName = "Smith", Date = DateTime.Now},
                };
            Header1 = "Header 1";
        }

        public ObservableCollection<Person> Persons { get; private set; }

        public string Header1 { get; set; }
    }
}

Person 类是从上面代码中的 Person 推导出的标准 poco。

信用:感谢Johan Larsson提供的大部分代码。他正在研究这个解决方案,我只是在帮忙,但他觉得我应该发布答案,因为 x:Static 是我的想法。

于 2013-01-21T18:20:50.450 回答