【问题标题】:How to change WPF control bindings at runtime如何在运行时更改 WPF 控件绑定
【发布时间】:2017-12-31 12:27:49
【问题描述】:

我的表单允许我添加和编辑记录(在不同的时间)。

目前我有一个保存按钮,用于提交对数据库的更改:

<Page.DataContext>
    <ViewModels:RecordsViewModel />
</Page.DataContext>

<Grid>
    <Button Name="btnSave" Content="Save" Comand="{Binding AddRecordCommand}" />
</Grid>

当我在我的 DataGrid 中单击以编辑记录时,记录数据将从数据库中获取并加载到每个分配的绑定的表单字段中。

不幸的是,这不会改变我保存按钮上的绑定,所以我尝试在我的代码中这样做:

// DataGrid edit button was clicked
private void btnEdit_Click(object sender, RoutedEventArgs e)
{
    btnSave.SetBinding(Button.CommandProperty, new Binding
    {
        Source = this.DataContext,
        Path = new PropertyPath("UpdateRecordCommand")
    });
    btnSave.CommandParameter = new Binding("Id");

    gList.Visibility = Visibility.Collapsed;
    gAddEdit.Visibility = Visibility.Visible;
}

不幸的是,这不起作用,绑定保持不变,以便将新记录保存到数据库中。

如何更改按钮的绑定,以便更新记录而不是添加新记录?

【问题讨论】:

  • 您可以使用 2 个按钮并根据条件更改它们的可见性。
  • @YvetteColomb 所以,让它检查,例如,if (Id != 0) { // edit record }?
  • 不,只是“如果 Id 存在则编辑”。我很担心如果 ViewModel 总是有一个 Id,比如说,如果我编辑一条记录,然后我想添加一个...假设我点击添加一条记录,它给了我更新视图,因为我之前更新了一个记录
  • 您的保存按钮能否循环通过ItemsSource 并挑选出添加的项目和编辑的项目?

标签: c# wpf mvvm data-binding controls


【解决方案1】:

如果您只是检查Id!=0

private void btnEdit_Click(object sender, RoutedEventArgs e)
{
    if (Id != 0)
    {
        // do your update code - do not touch the binding
        // Also this should call code from another class, 
        // it's better to separate out concerns within a project.
    }
    else
    {
        // do what you when there is an error - display a message to
        // the user. Load a specific page, reload this page.
    }

}

管理用户在添加或更新记录之间进行更改的更好方法是将这两个功能分开。这完全与您的程序流程和 UI 有关。分离创建或编辑功能要好得多。

如果您需要检查 Id 是否存在而它不存在 - 您可以加载创建页面。

【讨论】:

  • 你知道我在修改代码时注意到了什么吗?实际上,我根本没有在 Save 按钮上设置绑定。我在“添加”按钮上设置了绑定,我单击以调出用于添加新记录的表单
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-08
  • 1970-01-01
相关资源
最近更新 更多