[英]How to change WPF control bindings at runtime
我的表單允許我添加和編輯記錄(在不同時間)。
當前,我有一個保存按鈕,將更改提交到數據庫:
<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;
}
不幸的是,這不起作用,並且綁定保持不變,以便將新記錄保存到數據庫。
如何更改按鈕的綁定,以便它更新記錄而不是添加新記錄?
如果您只是檢查一個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是否存在-您可以加載創建頁面。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.