如何在WPF中将对象列表绑定到DataGrid

时间:2019-06-09 21:42:29

标签: c# wpf data-binding datagrid

这是我后面的代码:

public partial class MainWindow : INotifyPropertyChanged
{
    private List<Word> _words;

    public List<Word> Words
    {
        get => _words;
        set
        {
            _words = value;
            OnPropertyChanged("Words");
        }
    }

    public MainWindow()
    {
        InitializeComponent();

        MeaningGroup group1 = new MeaningGroup()
        {
            Synonyms = new List<string> {"synonym1", "synonym2", "synonym3"},
            Acronyms = new List<string> {"acronym1", "acronym2"}
        };

        MeaningGroup group2 = new MeaningGroup()
        {
            Synonyms = new List<string> { "synonym1"},
            Acronyms = new List<string> { "acronym1", "acronym2", "acronym3" }
        };

        MeaningGroup group3 = new MeaningGroup()
        {
            Synonyms = new List<string> { "synonym1", "synonym2" },
            Acronyms = new List<string> { }
        };

        MeaningGroup group4 = new MeaningGroup()
        {
            Synonyms = new List<string> { "synonym1" },
            Acronyms = new List<string> { "acronym1", "acronym2", "acronym3","acronym4" }
        };

        Word word1 = new Word() {Name = "word1",MeaningGroups = new List<MeaningGroup>() {group1, group2}};
        Word word2 = new Word() { Name = "word2", MeaningGroups = new List<MeaningGroup>() { group3, group4 } };
        Word word3 = new Word() { Name = "word3", MeaningGroups = new List<MeaningGroup>() { group1, group2,group4 } };
        Word word4 = new Word() { Name = "word4", MeaningGroups = new List<MeaningGroup>() { group3 } };

        Words = new List<Word> {word1, word2, word3, word4};

    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

public class Word
{
    public String Name { get; set; }
    public List<MeaningGroup> MeaningGroups { get; set; }

}

public class MeaningGroup
{
    public List<string> Synonyms { get; set; }
    public List<string> Acronyms { get; set; }
}

这是MainWindow.xaml代码:

<Window x:Class="WpfApp4.MainWindow"
    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"
    xmlns:local="clr-namespace:WpfApp4"
    DataContext="{Binding RelativeSource={RelativeSource Self}}"
    mc:Ignorable="d"
    Title="MainWindow" Height="450" Width="800">
<Grid>
    <DataGrid ItemsSource="{Binding Words}" AutoGenerateColumns="False">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
            <DataGridTextColumn Header="Synonym and acronyms">
               <!-- How binding? -->
            </DataGridTextColumn>
        </DataGrid.Columns>
    </DataGrid>
</Grid>

我想像这样绑定数据对象: enter image description here

3 个答案:

答案 0 :(得分:1)

我不太理解您的意思,但是如果您想将属性绑定到列,则可以执行以下操作:

<DataGrid ItemsSource="{Binding Words}">
   <DataGrid.Columns>
     <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
   </DataGrid.Columns>
</DataGrid>

现在,每个元素的“名称”将添加到此列。但是,如果要向一列添加多个属性,则必须添加DataGridTemplateColumn

<DataGrid ItemsSource="{Binding Words}">       
   <DataGrid.Columns>
      <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
      <DataGridTemplateColumn Header="Synonyms and Acronyms">
         <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
               <StackPanel>
                     //There will be all logic. For example
                     //<TextBlock Text="{Binding Synonyms}"/>
                     //<TextBlock Text="{Binding Acronyms}"/>
               </StackPanel>
            </DataTemplate>
         </DataGridTemplateColumn.CellTemplate>
      </DataGridTemplateColumn>
   </DataGrid.Columns>
</DataGrid>

但是抱歉,我不知道如果该列传递字符串集合(如您的示例)会发生什么。很抱歉,如果我误解了你

答案 1 :(得分:1)

您更新后的代码仍然存在绑定错误,您需要将此错误添加到构造函数的底部:

    this.DataContext = this;

您发布的代码的主要问题是,您试图将同义词和首字母缩写数组合并到一个列表中,这实际上是在将数据传递到视图层之前应该做的事情。我将使用转换器事后完成此任务,但请记住,这是您稍后可能需要修复的问题。

无论如何,您想要实现的目标都是相对简单的。使用DataGridTemplateColumn声明自定义列类型,并将其内容设置为ItemsControl(其默认面板为垂直StackPanel)。堆栈面板的每个元素都是一个MeaningGroup,因此只需使用另一个ItemsControl呈现标签,然后将其ItemsPanelTemplate设置为水平布局即可(我使用了WrapPanel)。将所有内容放在一起,您会得到:

<Window.Resources>

    <behaviors:ListUnionConverter x:Key="ListUnionConverter" />

    <DataTemplate x:Key="TagTemplate">
        <Border BorderBrush="Black" BorderThickness="1" CornerRadius="5" Margin="5" Padding="5">
            <TextBlock Text="{Binding}" />
        </Border>
    </DataTemplate>

    <DataTemplate x:Key="TagListTemplate">
        <ItemsControl ItemTemplate="{StaticResource TagTemplate}">
            <ItemsControl.ItemsSource>
                <MultiBinding Converter="{StaticResource ListUnionConverter}">
                    <Binding Path="Synonyms" />
                    <Binding Path="Acronyms" />
                </MultiBinding>
            </ItemsControl.ItemsSource>
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <WrapPanel />
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
        </ItemsControl>
    </DataTemplate>

    <DataTemplate x:Key="CellTemplate">
        <ItemsControl ItemsSource="{Binding MeaningGroups}" ItemTemplate="{StaticResource TagListTemplate}" />
    </DataTemplate>

</Window.Resources>

<Grid>
    <DataGrid ItemsSource="{Binding Words}" AutoGenerateColumns="False">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
            <DataGridTemplateColumn Header="Synonym and acronyms" IsReadOnly="True" CellTemplate="{StaticResource CellTemplate}" />
        </DataGrid.Columns>
    </DataGrid>
</Grid>

您还将需要用于将同义词和首字母缩写词合并到一个列表中的转换器的代码。同样,您应该用更可靠的替代品,或者最好修复数据结构以更好地满足视图要求:

结果:

public class ListUnionConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        return (values[0] as IEnumerable<string>).Concat(values[1] as IEnumerable<string>).ToArray();
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

enter image description here

更新:我刚刚注意到颜色要求不同。如果绝对必须,也可以使用转换器来执行此操作,但这是一个非常麻烦的解决方案。正确的方法是使用中间视图模型,并将同义词和首字母缩写词合并到一个列表中。

答案 2 :(得分:1)

下面的答案解决了这个问题,但是我会建议另一种方法。如上所述,首先需要在代码隐藏中添加DataContext = this。然后只需按如下所示更改xaml标记:

     <Grid>
        <DataGrid ItemsSource="{Binding Words}" AutoGenerateColumns="False">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
                <DataGridTemplateColumn Header="Synonym and acronyms">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <StackPanel>
                                <ItemsControl ItemsSource="{Binding MeaningGroups}">
                                    <ItemsControl.ItemTemplate>
                                        <DataTemplate>
                                            <StackPanel Orientation="Horizontal">
                                                <ItemsControl ItemsSource="{Binding Synonyms}">
                                                    <ItemsControl.ItemsPanel>
                                                        <ItemsPanelTemplate>
                                                            <WrapPanel/>
                                                        </ItemsPanelTemplate>
                                                    </ItemsControl.ItemsPanel>
                                                    <ItemsControl.ItemTemplate>
                                                        <DataTemplate>
                                                            <Border BorderThickness="1" BorderBrush="Black" CornerRadius="5" Margin="5 5 0 0">
                                                            <TextBlock Margin="3" Text="{Binding}"/>
                                                            </Border>
                                                        </DataTemplate>
                                                    </ItemsControl.ItemTemplate>
                                                </ItemsControl>
                                                <ItemsControl ItemsSource="{Binding Acronyms}">
                                                    <ItemsControl.ItemsPanel>
                                                        <ItemsPanelTemplate>
                                                            <WrapPanel/>
                                                        </ItemsPanelTemplate>
                                                    </ItemsControl.ItemsPanel>
                                                    <ItemsControl.ItemTemplate>
                                                        <DataTemplate>
                                                            <Border BorderThickness="1" BorderBrush="Black" CornerRadius="5" Background="Red" Margin="5 5 0 0">
                                                            <TextBlock Margin="3" Text="{Binding}"/>
                                                            </Border>
                                                        </DataTemplate>
                                                    </ItemsControl.ItemTemplate>
                                                </ItemsControl>
                                            </StackPanel>
                                        </DataTemplate>
                                    </ItemsControl.ItemTemplate>
                                </ItemsControl>
                            </StackPanel>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>

因此,我们将得到 enter image description here