如何在不丢失 WPF 中的绑定的情况下更改 TextBox.Text? [英] How do I change TextBox.Text without losing the binding in WPF?

查看:38
本文介绍了如何在不丢失 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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