简体   繁体   中英

How to change WPF control bindings at runtime

My form allows me to add and edit a record (at different times).

Currently I have a Save button which commits the changes to the database:

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

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

When I click in my DataGrid to edit a record, the record data is fetched from the database and loaded into the form fields per allocated bindings.

Unfortunately, this doesn't change the binding on my Save button, so I've tried to do it in my code:

// 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;
}

This, unfortunately, does not work and the binding remains unchanged so as to save a new record to the database.

How can I change my button's binding so that it'll update the record instead of adding a new one?

If you are just checking that an 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.
    }

}

The far better way to manage the user changing between adding or updating a record is to have these two functions separated. This is all about your program flow and UI. It is far better to separate a creation or edit functionality.

If you need to check if an Id exists and it does not - you can load a creation page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM