问题
I want to Refresh my DataGrid and found the following coding on the web:
dataGridView.ItemsSource = null;
dataGridView.ItemsSource = ItemsSourceObjects;
It does work except for the string/column Names does not get displayed with the objects only the objects/items itself.
Any Ideas on why this is happening?
EDIT:
<DataGridTextColumn Binding="{Binding TId}" Header="id" MinWidth="20" MaxWidth="60"/>
<DataGridTextColumn Binding="{Binding TChassisManufacturer}" Header="Project Name" MinWidth="122" MaxWidth="200"/>
<DataGridTextColumn Binding="{Binding ProjectStatusM}" Header="Status" MinWidth="122" MaxWidth="100"/>
回答1:
Here is an example:
You don't need to call refresh. When you add/delete items from my
, dg
will auto update for you.
XAML:
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1">
<DataGrid Name="dataGridView" ItemsSource="{Binding}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding TId}" Header="id" MinWidth="20" MaxWidth="60"/>
<DataGridTextColumn Binding="{Binding TChassisManufacturer}" Header="Project Name" MinWidth="122" MaxWidth="200"/>
<DataGridTextColumn Binding="{Binding ProjectStatusM}" Header="Status" MinWidth="122" MaxWidth="100"/>
</DataGrid.Columns>
</DataGrid>
</Window>
C#:
public partial class MainWindow : Window
{
ObservableCollection<myClass> my = new ObservableCollection<myClass>();
public MainWindow()
{
InitializeComponent();
dataGridView.DataContext = my;
my.Add(new myClass { TId = 1, TChassisManufacturer = "Sony", ProjectStatusM = "Done" });
my.Add(new myClass { TId = 2, TChassisManufacturer = "Apple", ProjectStatusM = "Doing" });
}
}
class myClass : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
int id;
public int TId
{
get
{
return id;
}
set
{
id = value;
if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("TId"));
}
}
string name;
public string TChassisManufacturer
{
get
{
return name;
}
set
{
name = value;
if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("TChassisManufacturer"));
}
}
string status;
public string ProjectStatusM
{
get
{
return status;
}
set
{
status = value;
if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("ProjectStatusM"));
}
}
}
来源:https://stackoverflow.com/questions/35576725/wpf-datagrid-refresh-displaymember-path-empty