WPF Datagrid刷新Displaymember路径为空

时间:2016-02-23 11:45:54

标签: c# wpf c#-4.0 datagrid wpf-controls

我想刷新我的DataGrid,并在网上找到以下编码:

dataGridView.ItemsSource = null;
dataGridView.ItemsSource = ItemsSourceObjects;

除了字符串/列之外它确实有效。名称不会与对象/项本身一起显示。

关于为什么会发生这种情况的任何想法?

修改

 <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 个答案:

答案 0 :(得分:0)

以下是一个例子:

您无需致电刷新。当您添加/删除my中的项目时,dg会自动为您更新。

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"));
        }
    }
}