如何在不丢失 WPF 中的绑定的情况下更改 TextBox.Text?

编程入门 行业动态 更新时间:2024-10-22 11:05:31
本文介绍了如何在不丢失 WPF 中的绑定的情况下更改 TextBox.Text?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在 WPF 应用程序中,我正在创建一个设置窗口来自定义键盘快捷键.

In a WPF application, I am creating a setting window to customize keyboard shortcuts.

在文本框中,我处理 KeyDown 事件并将 Key 事件转换为人类可读的形式(以及我想要保存数据的形式).

In the textboxes, I handle the KeyDown event and convert the Key event to a human readable form (and also the form in which I want to have my data).

文本框是这样声明的

<TextBox Text="{Binding ShortCutText, Mode=TwoWay}"/>

在事件处理程序中,我尝试同时使用

and in the event handler, I tried using both

(sender as TextBox).Text = "...";

(sender as TextBox).Clear(); (sender as TextBox).AppendText("...");

在这两种情况下,绑定回视图模型都不起作用,视图模型仍然包含旧数据并且不会更新.在另一个方向(从视图模型到文本框)绑定工作正常.

In both of these cases, the binding back to the viewmodel does not work, the viewmodel still contains the old data and does not get updated. Binding in the other direction (from viewmodel to the textbox) works fine.

有没有一种方法可以在不使用绑定的情况下从代码中编辑 TextBox.Text?还是我的流程中的其他地方有错误?

Is there a way I can edit the TextBox.Text from code without using the binding? Or is there an error somewhere else in my process?

推荐答案

var box = sender as TextBox; // Change your box text.. box.GetBindingExpression(TextBox.TextProperty).UpdateSource();

这应该会强制您的绑定更新.

This should force your binding to update.

更多推荐

如何在不丢失 WPF 中的绑定的情况下更改 TextBox.Text?

本文发布于:2023-11-02 14:42:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1552682.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:绑定   情况下   如何在   Text   WPF

发布评论

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

>www.elefans.com

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