C # WPF - How to always get the current text from a textbox?

I have a TextBox in FileWindow.xaml:

<TextBox x:Name="textBox" HorizontalAlignment="Left" Height="23" Margin="233,230,0,0" TextWrapping="Wrap" Text="{Binding FileName}" VerticalAlignment="Top" Width="120"/>

      

In ViewModel.cs:

public String FileName
{
    get { return _model.filename; }
    set
    {
        if (value != _model.filename)
        {
            _model.filename = value;
            OnPropertyChanged();
        }
    }
}

      

In Model.cs:

private String _filename = "example.txt";
public String filename { get { return _filename; } set { _filename = value; } }

      

I want that every time I enter text in the TextBox the _filename in Model.cs is updated.
The default text in the TextBox is example.txt, but if I change it, the filename in Model.cs doesn't change. What am I doing wrong?

+3
c # wpf mvvm xaml


source to share


2 answers


Try setting the UpdateSourceTrigger

binding property to PropertyChanged

:



Text="{Binding FileName, UpdateSourceTrigger=PropertyChanged}" 

      

+5


source to share


The TextBox was not immediately posted back to original code. Instead, the source was only updated after focus was lost in the TextBox. This behavior is controlled by a property on a named binding UpdateSourceTrigger

.

The default is Default, which basically means that the source is updated based on the property you are binding to.



The default is the UpdateSourceTrigger

default. Other options: PropertyChanged

, LostFocus

and Explicit

.

 <TextBox Text="{Binding FileName, UpdateSourceTrigger=PropertyChanged}" />

      

+4


source to share







All Articles
Loading...
X
Show
Funny
Dev
Pics