Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/333.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在运行时更改WPF控件绑定_C#_Wpf_Mvvm_Data Binding_Controls - Fatal编程技术网

C# 如何在运行时更改WPF控件绑定

C# 如何在运行时更改WPF控件绑定,c#,wpf,mvvm,data-binding,controls,C#,Wpf,Mvvm,Data Binding,Controls,我的表单允许我(在不同的时间)添加和编辑记录 目前,我有一个保存按钮,用于将更改提交到数据库: <Page.DataContext> <ViewModels:RecordsViewModel /> </Page.DataContext> <Grid> <Button Name="btnSave" Content="Save" Comand="{Binding AddRecordCommand}" /> </Gri

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

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

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

<Grid>
    <Button Name="btnSave" Content="Save" Comand="{Binding AddRecordCommand}" />
</Grid>
不幸的是,这不起作用,绑定保持不变,以便将新记录保存到数据库中


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

如果您只是检查
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是否存在,那么您可以加载一个创建页面。

如果您只是检查一个
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是否存在,则可以加载创建页面。

您可以使用两个按钮,并根据条件更改其可见性。@YvetteColomb因此,请检查,例如,
如果(Id!=0){//edit record}
?不,只需“编辑Id是否存在”。但是我担心ViewModel是否总是有一个Id,比如说,如果我编辑了一条记录,然后我想添加一条记录。。。假设我单击添加一条记录,它将为我提供更新视图,因为我以前更新了一条记录。您可以通过
ItemsSource
保存按钮循环,并选择添加的项目和编辑的项目吗?您可以使用两个按钮,并根据条件更改其可见性。@yvette因此,请检查,例如,
if(Id!=0){//edit record}
?不,只要“如果Id存在,请编辑”。但是我担心ViewModel是否总是有一个Id,比如说,如果我编辑了一条记录,然后我想添加一条记录。。。假设我单击添加一条记录,它会为我提供更新视图,因为我以前更新了一条记录。您的保存按钮是否可以在
ItemsSource
中循环,并选择添加的项和编辑的项?您知道我在更改代码时注意到了什么吗?实际上,我根本没有在保存按钮上设置绑定。我在“添加”按钮上设置了绑定,我点击该按钮打开了用于添加新记录的表单你知道我在修改代码时注意到了什么吗?实际上,我根本没有在保存按钮上设置绑定。我在“添加”按钮上设置绑定,我单击该按钮打开用于添加新记录的表单