将DataTable绑定到DataGrid C#WPF MVVM

时间:2017-05-20 20:53:12

标签: c# wpf mvvm data-binding wpfdatagrid

MVVM的新手,在尝试将动态生成的DataTable与DataGrid绑定时,努力弄清楚出错的地方。我找到了一些解决方案,并试图根据以前的回复对我的实现进行调整:

XAML:

<DataGrid x:Name="Grid" Margin="5,0,0,0" ItemsSource="{Binding dataTable, Mode=TwoWay}" AutoGenerateColumns="False" VerticalAlignment="Center">
<DataGrid.Columns>
    <DataGridTextColumn Header="Header1" Binding="{Binding Column1Name}"/>
    <DataGridTextColumn Header="Header2" Binding="{Binding Column2Name}"/>
</DataGrid.Columns>
<DataGrid.DataContext>
    <ViewModels:Presenter/>
</DataGrid.DataContext>

XAML CS:

DataTable dataTable = new DataTable();
Grid.DataContext = dataTable.DefaultView;
//I don't believe I should be using System.Data in View?

视图模型

.Presenter:

public class Presenter : ObservableObject {
private DataTable _dataTable;


public DataTable dataTable
    {
        get { return _dataTable; }
        set
        {
            _dataTable = value;
            RaisePropertyChangedEvent("Grid");
        }
    }

private void ParseData()
    {
        if (string.IsNullOrWhiteSpace(ID)) return;
        dataTable = DataParser.ParseURL(ID);
    }
}

.ObservableObject

public class ObservableObject : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected void RaisePropertyChangedEvent(string propertyName)
    {
        var handler = PropertyChanged;
        if (handler != null)
            handler(this, new PropertyChangedEventArgs(propertyName));
    }
}

我知道模型中的数据正确返回,当我在调试器中时,RaisePropertyChangedEvent正在触发,但视图没有被更新。

2 个答案:

答案 0 :(得分:2)

您提出错误的PropertyName(这似乎是XAML中Grid的名称。

在调用"dataTable"方法时提出姓名RaisePropertyChanged

像这样:

public DataTable dataTable
{
    get { return _dataTable; }
    set
    {
        _dataTable = value;
        RaisePropertyChangedEvent("dataTable");
    }
}

您可以做的其他一些事情是:

  • [CallerMemberName]参数之前使用propertyName属性。这将节省您必须提供它,因为它检测到什么属性正在调用它(C#5及以上) - 例如:protected void RaisePropertyChangedEvent([CallerMemberName] string propertyName)
  • PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));方法中使用RaisePropertyChanged。这样您就不必创建变量并检查null(C#6及以上)
  • 将您的dataTable属性重命名为DataTable - 它可以更清晰地说明属性和字段是什么,并且在C#中这是常见的事情

希望这会有所帮助:)

答案 1 :(得分:2)

由于您将DataContext的{​​{1}}设置为DataGrid的{​​{1}},所以:

DataView

...你应该直接绑定到DataTable

Grid.DataContext = dataTable.DefaultView;

如果要绑定到DataContext媒体资源,则应将<DataGrid x:Name="Grid" Margin="5,0,0,0" ItemsSource="{Binding}" AutoGenerateColumns="False" VerticalAlignment="Center"> ... 设置为dataTable课程的实例:

DataContext
Presenter

然后,您可以将var p = new Presenter(); Grid.DataContext = p; 对象的<DataGrid x:Name="Grid" Margin="5,0,0,0" ItemsSource="{Binding dataTable}" AutoGenerateColumns="False" VerticalAlignment="Center"> 属性设置为新的dataTable

Presenter

您仍然需要按照@Geoff James的建议修改您的财产:

DataTable