You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WPF .NET6.0中NotifyOfPropertyChange无法实时更新绑定TextBox问题

WPF双TextBox实时同步失效修复

问题根因

你的绑定配置存在三个错误,直接导致同步逻辑不符合预期:

  • 第一个TextBox绑定显式设置了Mode=OneWay,该模式仅支持ViewModel属性更新UI,UI输入无法回写到ViewModel,无法触发反向同步。
  • WPF的TextBox.Text绑定默认UpdateSourceTrigger为LostFocus,即只有控件失去焦点时才会把输入内容提交到绑定源,因此输入过程中不会实时更新。
  • 第二个TextBox仅设置了x:Name属性,完全没有和ViewModel的Name属性建立绑定关系,输入内容和ViewModel完全脱节,修改它自然不会同步到第一个文本框。

修复后的代码

ShellView.xaml

<Window x:Class="WpfApp3.Views.ShellView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfApp3.Views"
    mc:Ignorable="d"
    Title="ShellView" Height="450" Width="450">
<Grid>
    <StackPanel>
        <TextBox Text="{Binding Path=Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
        <TextBox Text="{Binding Path=Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
        <Button Content="Click Me" />
    </StackPanel>
</Grid>
</Window>

ShellViewModel.cs

原有ViewModel代码逻辑正确,无需修改:

public class ShellViewModel : PropertyChangedBase
{
    string name = "";

    public string Name
    {
        get { return name; }
        set
        {
            name = value;
            NotifyOfPropertyChange(() => Name);
        }
    }
}

配置说明

  • Mode=TwoWay:开启双向绑定通道,既支持ViewModel属性变化更新UI,也支持UI输入回写ViewModel。
  • UpdateSourceTrigger=PropertyChanged:将回写触发时机从默认的失焦改为输入内容变化立刻触发,实现输入过程中实时同步。
  • 两个TextBox都绑定到同一个Name属性,任意一个输入修改都会立刻更新属性值,再通过属性变更通知同步到另一个文本框。

内容的提问来源于stack exchange,提问作者Diyari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 02:18:03