How to change TextBox.Text without losing binding in WPF?

In a WPF application, I create a settings window for customizing keyboard shortcuts.

In text boxes, I handle the KeyDown event and convert the Key event to a human-readable form (as well as the form in which I want to have my data).

The text field is declared as follows

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

and in the event handler I tried to use both

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

and

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

In both cases, binding to the viewmodel does not work, the viewmodel still contains old data and is not updated. Linking in the other direction (from the viewmodel to the text box) works fine.

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

+5
source share
6 answers
var box = sender as TextBox;
// Change your box text..

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

.

+8

Text - , .

+3

:

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

.

, .

: textbox1.Text = String.empty

: textbox1.Clear()

+1

TextBox ! (ShortCutText). IsReadOnly= " True" TextBox.

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

INotifyPropertyChanged , MSDN:

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

Change the settings of your ShortCutText property (to which your TextBox is bound):

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 automatically subscribes to the PropertyChanged event. Now use the KeyDown TextBox event, for example:

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

If you use MVVM, you should not change the Text property for the TextBox from the code, change the value in the view model, and the template will complete its task, synchronizing the view.

0
source

All Articles