当我点击button1加载了数据网格,但为什么我的文本(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;
}
我的button1后面的代码:
private void button1_Click(object sender, RoutedEventArgs e)
{
dataGrid.ItemsSource = CreateDataTable();
}
告诉我是否需要更多信息,请帮助我!
答案 0 :(得分:0)
您的XAML代码没有绑定到您要显示的属性。使用AutoGenerateColumns =&#34; False&#34;这是必须的。 至少您的类需要为要在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; }}
答案 1 :(得分:0)
好吧,你必须为你手动定义的每一列启用autogeneratecolumns或设置Bindings。