如何在WPF中有选择地更新模型 [英] How to selectively update a model in wpf

查看:89
本文介绍了如何在WPF中有选择地更新模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

单击listviewitem时,我有一个模型列表显示在listview中。我打开一个对话框,该对话框绑定到listviewitem的数据模型,并允许用户编辑各种属性。



我试图弄清楚如何处理确定和取消按钮。一方面,如果我将对话框直接绑定到listviewitem的模型,似乎没有办法取消该操作。



如果另一方面,我给对话框一个模型(而不是真正的模型)的克隆(由于使模型可克隆而产生的开销) cancel很容易处理,但是将新数据放入现有模型很麻烦,因为然后我必须经历所有操作,然后将克隆中的所有属性复制回原始模型中。



解决方案

您可以将所有绑定更改为显式,因为它们不会自动推送值回到源代码,然后单击确定按钮时强制它们更新。



例如,让我们使用一个显式控件将TextBox绑定到模型的 Foo属性。更新模式:

 < TextBox x:Name = fooEdit Text = {Binding Foo,UpdateSourceTrigger = Explicit} / > 

然后,当单击确定按钮时:

  BindingExpression be = fooEdit.GetBindingExpression(TextBox.TextProperty); 
be.UpdateSource();

如果您有很多控制权,这可能会有些麻烦,但是它可以让您完全控制当从其绑定控件中更新基础属性时。



更新



I应该补充一点,您还应该查看 IEditableObject 界面,该界面专为您描述的场景而设计。如果您可以在模型或中间ViewModel上实现该功能,那将使工作变得更加轻松。


I have a list of models displayed in a listview when the listviewitem is clicked I open a dialog that is bound to the listviewitem's data model and allows the user to edit the various properties.

I am trying to figure how to deal with the ok and cancel buttons. On the one hand if I bind the dialog directly to the listviewitem's model there doesn't seem to be a way to cancel the operation.

If on the other hand I give the dialog a clone (not so hip on this because of the overhead of making my model cloneable) of the model instead of the real one cancel is easy to handle but getting the new data into existing model is pain because then I have to go through and copy all the properties from the clone back into the original model.

I suspect there a good design pattern for this. Any ideas?

解决方案

You can change all your bindings to be "explicit", in that they don't automatically push the value back to the source, and then force them to update when the OK button is clicked.

For example, let's bind a TextBox to the model's "Foo" property with an explicit update mode:

<TextBox x:Name="fooEdit" Text="{Binding Foo,UpdateSourceTrigger=Explicit}" />

Then when the OK button is clicked:

BindingExpression be = fooEdit.GetBindingExpression(TextBox.TextProperty);
be.UpdateSource();

This can be a little bit cumbersome if you have lots of controls, but it gives you total control over when the underlying properties are updated from their bound controls.

Update

I should add that you should also look at the IEditableObject interface, which is designed for the scenario you describe. If you can implement that on your model, or an intermediate ViewModel, that makes life much easier.

这篇关于如何在WPF中有选择地更新模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆