【发布时间】:2019-06-09 21:42:29
【问题描述】:
这是我的代码:
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>
【问题讨论】:
-
对于初学者,您的主列表绑定有问题,您正在创建一个名为
Words的局部变量并将其设置为 DataContext,但随后您的ItemsControl正在尝试绑定到名为Words的属性 要么将Words设为MainWindow 的属性并将其设置为您的DataContext,要么将绑定更改为Binding="{Binding}"。除此之外,除了最终将同义词和首字母缩略词的折叠联合呈现为标签的单列列表或其他内容之外,您真的不清楚您要做什么? -
@MarkFeldman 我已经更新了代码。请重新审核。
标签: c# wpf data-binding datagrid