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

WPF单ViewModel绑定异常:主窗口TextBox无法同步到子窗口

WPF数据绑定问题:主窗口TextBox与子窗口TextBlock同步失效

我在WPF中尝试将主窗口TextBox的文本绑定到子窗口的TextBlock,实现主窗口输入时子窗口实时展示数据。调试发现主窗口TextBox已正确绑定到MainWindowViewModel,但子窗口完全无响应。

App.xaml.cs 代码

public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        var window = new MainWindow() { DataContext = new MainWindowViewModel() };
        window.Show();

        base.OnStartup(e);
    }
}

主窗口(MainWindow.xaml.cs)代码

public partial class MainWindow : Window
{
    public MainWindow()
    {
        var viewModel = new MainWindowViewModel();
        ChildWindow childWindow = new ChildWindow();
        childWindow.DataContext = viewModel;
        childWindow.Show();
        InitializeComponent();
        DataContext = viewModel;
    }
}

MainWindowViewModel 代码

public class MainWindowViewModel : ViewModelBase
{
    public string _firstTeamName { get; set; }
    public string FirstTeamName
    {
        get { return _firstTeamName; }
        set
        {
            _firstTeamName = value;
            OnPropertyChanged(nameof(FirstTeamName));
        }
    }
}

ViewModelBase 代码

public abstract class ViewModelBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        var handler = this.PropertyChanged;
        if (handler != null)
        {
            handler(this, e);
        }
    }
}

主窗口XAML绑定代码

<TextBox x:Name ="firstTeam"  Height="30" VerticalAlignment="Top" Text ="{Binding FirstTeamName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>

子窗口XAML绑定代码

<TextBlock Text ="{Binding FirstTeamName}" FontSize="24"></TextBlock>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 04:27:28