如何更改TextBox.Text不失绑定在WPF?(How do I change TextBox.

2019-09-22 04:29发布

在WPF应用程序,我创建一个设置窗口自定义快捷键。

在文本框,我处理KeyDown事件和关键事件转换为人类可读的形式(和形式,我希望有我的数据)。

文本框声明如下

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

而在事件处理程序,我试图同时使用

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

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

在这两种情况下,结合回视图模型不能正常工作,该视图模型仍包含旧数据并没有更新。 在另一个方向(从视图模型到文本框)绑定工作正常。

有没有一种方法,我可以编辑从代码TextBox.Text不使用绑定? 还是有一个错误在其他地方在我的过程吗?

Answer 1:

var box = sender as TextBox;
// Change your box text..

box.GetBindingExpression(TextBox.TextProperty).UpdateSource();

这应该迫使你的绑定更新。



Answer 2:

不要更改Text属性 - 改变你所绑定。



Answer 3:

这确实的伎俩:

private static void SetText(TextBox textBox, string text)
    {
        textBox.Clear();
        textBox.AppendText(text);
        textBox.GetBindingExpression(TextBox.TextProperty).UpdateSource();
    }


Answer 4:

客人不愿意需要在所有的修改文本框的值! 在代码中,你只需要修改相关的值(ShortcutText下 ),您也可以将您的文本框的IsReadOnly =“TRUE”属性。

<TextBox Text="{Binding Path=ShortCutText,Mode=OneWay}" 
         KeyDown="TextBox_KeyDown" IsReadOnly="True"/>

你应该意识到INotifyPropertyChanged接口在类在MSDN描述:

http://msdn.microsoft.com/library/system.componentmodel.inotifypropertychanged.aspx

修改您的ShortcutText下财产(到你的文本框绑定到)的setter方法:

class MyClass:INotifyPropertyChanged
{
    string shortCutText="Alt+A";
    public string ShortCutText
    {
         get { return shortCutText; } 
         set 
             { 
                  shortCutText=value; 
                  NotifyPropertyChanged("ShortCutText");
             }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    void NotifyPropertyChanged( string props )
    {
        if( PropertyChanged != null ) 
            PropertyChanged( this , new PropertyChangedEventArgs( prop ) );
    }

}

WPF将自动订阅PropertyChanged事件。 现在,使用文本框的KeyDown事件,例如,像这样的:

private void TextBox_KeyDown( object sender , KeyEventArgs e )
{
    ShortCutText = 
        ( e.KeyboardDevice.IsKeyDown( Key.LeftCtrl )? "Ctrl+ " : "" )
        + e.Key.ToString( );
}


Answer 5:

我也有类似的情况。

当我清除该文本框失去约束力。

我穿着: textbox1.Text = String.empty

我改变了这一点: textbox1.Clear()

这是点我的解决办法



Answer 6:

如果您使用的MVVM,你不应该从代码TextBox的Text属性更改,在视图模型改变的价值和格局将完成其工作同步视图。



Answer 7:

您可以在XAML本身进行配置:

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

UpdateSourceTrigger =的PropertyChanged



文章来源: How do I change TextBox.Text without losing the binding in WPF?
标签: c# wpf mvvm