【问题标题】:XAML textbox updated when TextChanged eventTextChanged 事件时更新 XAML 文本框
【发布时间】:2012-07-16 08:44:30
【问题描述】:

我使用 XAML 和数据绑定 (MVVM)。当我的用户在 TextBox 中写入新的文本字符时,我需要更新标签。

XAML

    <Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <TextBox Height="23" HorizontalAlignment="Left" Margin="12,12,0,0" Name="textBox1" VerticalAlignment="Top" Width="463" Text="{Binding OriginalText}"/>
        <Label Height="28" HorizontalAlignment="Left" Margin="12,41,0,0" Name="label1" VerticalAlignment="Top" Width="463" Content="{Binding ModifiedText}"/>
        <Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="400,276,0,0" Name="button1" VerticalAlignment="Top" Width="75" />
    </Grid>
</Window>

视图模型

    class MainViewModel : NotifyPropertyChangedBase
    {
        private string _originalText = string.Empty;
        public string OriginalText
        {
            get { return _originalText; }
            set
            {
                _originalText = value;
                NotifyPropertyChanged("OriginalText");
                NotifyPropertyChanged("ModifiedText");
            }
        }

        public string ModifiedText
        {
            get { return _originalText.ToUpper(); }
        }
    }

我在 XAML 中添加了一个按钮。该按钮什么都不做,只是帮助我失去了文本框的焦点。当我失去焦点时,绑定会更新,上面的文本会出现在我的标签中。但是数据绑定只有在文本失去焦点时才会更新。 TextChanged 事件不会更新绑定。我想强制更新 TextChanged 事件。我怎样才能做到这一点?我应该使用什么组件?

【问题讨论】:

    标签: c# .net xaml data-binding


    【解决方案1】:
     <TextBox Name="textBox1"
          Height="23" Width="463"
          HorizontalAlignment="Left" 
          Margin="12,12,0,0"   
          VerticalAlignment="Top"
          Text="{Binding OriginalText, UpdateSourceTrigger=PropertyChanged}" /> 
    

    MSDN How to: Control When the TextBox Text Updates the Source:

    TextBox.Text 属性的默认 UpdateSourceTrigger 值为 失去焦点。这意味着如果应用程序有一个带有 数据绑定 TextBox.Text 属性,您在 TextBox 中键入的文本 在 TextBox 失去焦点之前不会更新源(对于 例如,当您单击离开文本框时)。

    如果您希望源在您输入时得到更新,请设置 UpdateSourceTrigger 绑定到 PropertyChanged。在里面 下面的示例中,TextBox 和 TextBlock 绑定到相同的源属性。这 TextBox 绑定的 UpdateSourceTrigger 属性设置为 属性已更改。

    【讨论】:

    • 谢谢。我认为您犯了一个小错误,因为您的解决方案不起作用,但这对我来说是正确的 Text="{Binding OriginalText, UpdateSourceTrigger=PropertyChanged}"
    • 在 UWP Windows 10 应用程序中,我还必须添加 Mode=TwoWay。 Text="{绑定 OriginalText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
    • 在 UWP Windows 10 应用程序中,我还必须添加 Mode=TwoWay。 Text="{Binding OriginalText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多