当我单击按钮1时,数据网格加载,但为什么我的文本(text1和name1)没有显示在datagrid的单元格中?
其设计规范:
<DataGrid AutoGenerateColumns="False" Height="200" Name="dataGrid" Width="200">
<DataGrid.Columns>
<DataGridTextColumn Header="Name" />
<DataGridCheckBoxColumn Header="visible" />
<DataGridTextColumn Header="Header" />
</DataGrid.Columns>
</DataGrid>
它的背后代码:
public class DataGridStructure
{
public bool visible { get; set; }
public string NameField { get; set; }
public string HeaderText { get; set; }
}
public List<DataGridStructure> CreateDataTable()
{
List<DataGridStructure> dgs = new List<DataGridStructure>();
dgs.Add(new DataGridStructure() {HeaderText="text1", NameField="name1", visible=true});
return dgs;
}
我的按钮1的后面代码:
private void button1_Click(object sender, RoutedEventArgs e)
{
dataGrid.ItemsSource = CreateDataTable();
}
告诉我是否需要更多信息,请帮助我!
XAML 代码没有绑定到要显示的属性。使用AutoGenerateColumns="False",这是必须的。至少您的类需要为要在 DataGrid 中显示的属性实现 INotifyPropertyChanged 接口。您也不应该使用 List 绑定到 ItemsSource,而应该使用 ObservableCollection。
XAML 应如下所示:
<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding MyItemsSource}" Height="200" Name="dataGrid" Width="200">
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding Name}" />
<DataGridCheckBoxColumn Header="Visible" Binding="{Binding visible}" />
<DataGridTextColumn Header="Header" Binding="{Binding Header}" />
</DataGrid.Columns>
</DataGrid>
以及背后的代码:
public class DataGridStructure : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
private bool _visible = false;
public bool visible {
get{ return _visible; }
set{
_visible = value;
set{ OnPropertyChanged("visible");
}
}
private string _nameField = string.Empty;
public bool NameField {
get{ return _nameField; }
set{
_nameField = value;
set{ OnPropertyChanged("NameField");
}
}
private string _headerText = string.Empty;
public bool HeaderText {
get{ return _headerText; }
set{
_headerText = value;
set{ OnPropertyChanged("HeaderText");
}
}
}
public void CreateDataTable()
{
MyItemsSource.Add(new DataGridStructure() {HeaderText="text1", NameField="name1", visible=true});
}
private void button1_Click(object sender, RoutedEventArgs e)
{
DataContext = this;
}
private ObservableCollection<DataGridStructure> _dataGridStructure = new ObservableCollection<DataGridStructure>();
public ObservableCollection<DataGridStructure> MyItemsSource{get{ return _dataGridStructure; }}
好吧,您必须启用自动生成列或为您手动定义的每个列设置绑定。