如何把我的数据到DataGrid
本文关键字:DataGrid 数据 我的 | 更新日期: 2023-09-27 18:04:54
我想创建一个DataGrid,它将显示我的列表中的数据:
public List<HeaderTagControlsPair> HeaderTagControlsPairList = new List<HeaderTagControlsPair>();
这是我的类HeaderTagControlsPair
:
public class HeaderTagControlsPair
{
public TextBlock HeaderTextBlock = new TextBlock
{
Margin = new System.Windows.Thickness(10,10,10,10)
};
public ComboBox TagComboBox = new ComboBox();
public RadioButton TimeRadioButton = new RadioButton
{
GroupName = "TimeRadioButtons",
HorizontalAlignment = HorizontalAlignment.Center
};
}
因此,我希望我的DataGrid将列表中的每个项目显示为新记录。正如你可以在我的类中看到的,每条记录应该有:一个textBlock,一个ComboBox和一个RadioButton。
我试了如下:
DataGrid MainDataGrid = new DataGrid();
MainDataGrid.ItemsSource = settings.HeaderTagControlsPairList;
this.Content = MainDataGrid; //display MainDataGrid in the window
不幸的是,我得到一个没有记录的空窗口。
如果可能的话,我想在c#中从代码背后做整个思考。我不太懂XAML。但是如果你认为这应该在XAML中完成-我会做的。
要使它按照您想要的方式工作,您需要阅读相当多的内容。MVVM设计模式,DataGrid
控件,数据绑定,INotifyPropertyChanged
接口,等等。
首先,您不将Controls
绑定到DataGrid
,您将绑定数据。下面显示的是DataGrid
控件的XAML:
<DataGrid ItemsSource="{Binding Path=HeaderTagControlsPairList}"
AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Header" Binding="{Binding Path=Header}"/>
<DataGridComboBoxColumn Header="Tag" ItemsSource="{Binding Path=Tags}"/>
<DataGridCheckBoxColumn Header="Time" Binding="{Binding Path=Time}"/>
</DataGrid.Columns>
</DataGrid>
DataGrid
的ItemsSource
应该绑定到HeaderTagControlsPair
对象列表。此列表需要在实现INotifyPropertyChanged
接口的类中,以便在DataGrid
中正确显示和更新数据。
HeaderTagControlsPair
类本身看起来像这样:
public class HeaderTagControlsPair
{
public string Header { get; set; }
public List<string> Tags { get; set; }
public bool Time { get; set; }
}
将包含数据,而不是控件。将显示此数据的实际控件在上面XAML中的DataGrid
列中定义。
这个例子是不完整的,因为您需要正确地设置和实现包含HeaderTagControlsPairList
的类。这是你需要做一些研究的东西,这样你就能理解它是如何工作的。阅读一些我上面提到的主题将为您提供正确实现此功能所需的背景知识,并理解为什么需要所有额外的步骤。