c# - 如何在运行时更改 WPF 控件绑定(bind)

标签 c# wpf mvvm data-binding controls

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

目前我有一个保存按钮,它将更改提交到数据库:

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

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

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

不幸的是,这不会改变我的保存按钮上的绑定(bind),所以我尝试在我的代码中这样做:
// 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;
}

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

如何更改按钮的绑定(bind)以更新记录而不是添加新记录?

最佳答案

如果您只是检查 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 是否存在而它不存在 - 您可以加载创建页面。

关于c# - 如何在运行时更改 WPF 控件绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45305659/

相关文章:

wpf - Autofac:将 LifeTimeScope 与 MVVM 中 ViewModel 的生命周期相关联

c# - 无法将 'System.TimeSpan?' 隐式转换为 'System.TimeSpan'

c# - 在基于 MVVM 的应用程序中管理分层对象状态的最佳方法/方法是什么?

c# - 如何创建 Entity Framework 模型第一个关联表?

c# - 如何在 WPF 中以编程方式设置 clr 命名空间属性

C# WPF - 如何组合数据触发器和触发器?

C# - WPF 在 DataGridColumnHeader 中使用 DataTrigger

Swift - 如何使用闭包在 View 模型中触发函数?

c# - 检测计算机上是否启用了链接层拓扑

c# - 如何去除 Visual Studio 2017 15.8 版中的水平白线?