【问题标题】:Modify View after Binding Command Executes绑定命令执行后修改视图
【发布时间】:2019-07-15 13:16:32
【问题描述】:

我有一个DataGrid 和两个按钮。按第一个按钮将调用一个命令,该命令使用DataTable 从数据库表中填充我的DataGrid。第二个按钮将应用一些逻辑并最终从数据库表中删除数据。我的问题是,在我选择第二个按钮后,DataGrid 没有更新,仍然显示数据库中不存在的行。这是我的设置:

Button1(填充 DataGrid):

<Button Content="Load Data" Command="{Binding FillMyDataTableCommand}"/>

数据网格:

<DataGrid ItemsSource="{Binding MyDataTable}">

Button2(应用逻辑,数据不应该再出现在表中):

<Button Command="{Binding StartCommand}" CommandParameter="{Binding ElementName=myDataGrid}"</Button>

在选择 button2 时,我的 ViewModel 负责逻辑,在逻辑之后我想更新数据网格以显示对表的更改:

myDataGrid.Items.Refresh();

我不能在 ViewModel 中执行此操作,因为这会违反 MVVM,因为它应该对视图一无所知。我尝试了一种解决方法,方法是使用单击命令添加按钮背后的代码,希望它会在绑定命令之后执行。但是它首先执行:

Button2(尝试):

<Button Command="{Binding StartCommand}" CommandParameter="{Binding ElementName=myDataGrid}" click="button_click_Refresh"</Button>

我该如何解决这个问题?

【问题讨论】:

标签: c# wpf xaml mvvm


【解决方案1】:

我记得也有这个问题。

我想出了两个对我有用的解决方案:

  • 将我的 DataGrid 的 ItemSource 的数据类型更改为 ObservableCollection,它会在集合更改时更新 UI。

  • 在数据需要更改时覆盖我的 ItemSource。例如,当我想从数据库中检索不同的数据时,分配一个新的 DataTable 作为 ItemSource。

【讨论】:

    【解决方案2】:

    定义了MyDataTable 属性的视图模型应该实现INotifyPropertyChanged 接口。

    然后您可以修改DataTableDataView 并在视图模型中为MyDataTable 属性引发PropertyChanged 事件以刷新视图中的DataGrid

    //update datatable...
    //and raise the event when you're done:
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(MyDataTable)));
    

    【讨论】:

    • 我访问的DataTable 是我的DataSet 的一部分,它在.xsd 文件中使用SQL 查询。我的ViewModel 实现了INotifyPropertyChanged 但是,我不确定PropertyChanged? 行的位置。
    • @TheGreatZab:例如在MyDataTable的setter中。
    猜你喜欢
    • 2012-10-13
    • 2016-09-19
    • 1970-01-01
    • 2012-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-05
    相关资源
    最近更新 更多