简体   繁体   English

C#WPF - 如何始终从文本框中获取当前文本?

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

I have a TextBox in FileWindow.xaml : 我在FileWindow.xaml中有一个TextBox:

<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: 在ViewModel.cs中:

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

In Model.cs: 在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. 我希望每次输入TextBox时,Model.cs中的_filename都会更新。
The default text in the TextBox is example.txt, but if I change it, the _filename in Model.cs doesn't change. TextBox中的默认文本是example.txt,但如果我更改它,Model.cs中的_filename不会更改。 What am I doing wrong? 我究竟做错了什么?

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

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

TextBox was not immediately sent back to the source. TextBox没有立即发送回源。 Instead, the source was updated only after focus was lost on the TextBox. 相反,只有在TextBox上丢失焦点后才更新源。 This behavior is controlled by a property on the binding called UpdateSourceTrigger . 此行为由名为UpdateSourceTrigger的绑定上的属性控制。

It defaults to the value "Default", which basically means that the source is updated based on the property that you bind to. 它默认为“Default”值,这基本上意味着根据绑定的属性更新源。

Default is, obviously, the default value of the UpdateSourceTrigger . 显然,默认值是UpdateSourceTrigger的默认值。 The other options are PropertyChanged , LostFocus and Explicit . 其他选项是PropertyChangedLostFocusExplicit

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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