Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

mvvm

wpf

xaml

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 type in the TextBox, the _filename in Model.cs gets 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?

like image 796
Esad Avatar asked Jan 05 '23 05:01

Esad


1 Answers

Try to set the UpdateSourceTrigger property of the binding to PropertyChanged:

Text="{Binding FileName, UpdateSourceTrigger=PropertyChanged}" 
like image 170
mm8 Avatar answered Jan 10 '23 12:01

mm8