如何编辑ViewModel对象的属性,但仅在单击视图中的按钮时应用更改(How to edit properties of a ViewModel object but only apply chan

编程入门 行业动态 更新时间:2024-10-26 01:26:35
如何编辑ViewModel对象的属性,但仅在单击视图中的按钮时应用更改(How to edit properties of a ViewModel object but only apply changes when clicking a button in the View)

我的屏幕有一个Person类型的对象列表,以及一个通过数据绑定显示人员属性(名称,地址,重量等)的表单。

我希望能够:

单击“编辑属性”按钮,然后开始修改人员的属性(我已经可以使用ViewModel中的Command执行此操作); 如果我单击“取消”,编辑的信息“回滚”到该人的原始未修改值; 如果我单击“保存更改”,那么此人的姓名将在人员列表中更改。

我现在的问题是,当我正在编辑表单时,原始属性会更新,所以说,实时,如果我决定取消,我没有原始值“返回”。

我考虑Clone选定的人,但这似乎很奇怪。 我认为更好的方法是仅更改字段的文本属性,并仅在单击提交更改时更新回来,但我不知道如何操作,特别是如何保持数据绑定一致性。

My screen has a list of objects of type Person, and a form that displays the person properties (name, address, weight, etc.) via databinding.

I want to be able to:

Click in a button "Edit properties", and start modifying the person's properties (I can already do that using Commands in the ViewModel); If I click "Cancel", the edited info "rollback" to the original unmodified values of that person; If I click "Save changes", JUST THEN the person's name changes in the person list.

My problem right now is that, as I am editing the forms, the original properties are updated, so to say, in realtime, and if I decide to cancel, I have not the original values to "go back".

I considered to Clone the selected person, but that seemed to be odd. I think a better approach would be to change only the text properties of the field, and update back only when clicking to submit changes, but I don't know how to do it, specially how to preserve databinding consistency.

最满意答案

绑定时,使用UpdateSourceTrigger = Explicit 。 这将告诉XAML在你告诉它之前不要更新源绑定。 然后,当单击“保存”按钮时,可以在绑定上调用UpdateSource以将控件的内容推送回Person对象,如:

var nameBinding = nameTextBox.GetBindingExpression( TextBox.TextProperty ); nameBinding.UpdateSource();

要取消,请改用UpdateTarget ,它会将Person对象中的数据推送回您的控件。

When you bind, use UpdateSourceTrigger=Explicit. That will tell XAML not to update the source binding until you tell it to. Then, when your Save button is clicked, you can call UpdateSource on the binding to push the contents of your controls back to the Person object, something like:

var nameBinding = nameTextBox.GetBindingExpression( TextBox.TextProperty ); nameBinding.UpdateSource();

To cancel, use UpdateTarget instead, which will push the data in the Person object back to your control.

更多推荐

本文发布于:2023-08-02 22:13:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1381526.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:视图   时应   单击   按钮   属性

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!