简体   繁体   中英

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 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?

尝试将绑定的UpdateSourceTrigger属性设置为PropertyChanged

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

TextBox was not immediately sent back to the source. Instead, the source was updated only after focus was lost on the TextBox. This behavior is controlled by a property on the binding called UpdateSourceTrigger .

It defaults to the value "Default", which basically means that the source is updated based on the property that you bind to.

Default is, obviously, the default value of the UpdateSourceTrigger . The other options are PropertyChanged , LostFocus and Explicit .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM