数据并非在所有绑定上都更新

时间:2019-08-09 06:45:46

标签: c# wpf data-binding

我有两个Windows,分别是MainWindow和CounterWindow;在MainWindow上是具有绑定的按钮,在我的CounterWindow上是具有相同绑定的标签

检索数据时,Button确实会接收新数据,但是CounterWindow标签不会更新。

注意,初始化时它变为0(因此Binding函数!(?))

    public class CounterModel : INotifyPropertyChanged
    {
        public string CurrentCount {
            get { return mCurrentCount; }
            set
            {
                if (value == mCurrentCount) return;
                mCurrentCount = value;
                OnPropertyChanged();
            }

        }

        public CounterModel() {
            UpdateCounters();
        }

        public event PropertyChangedEventHandler PropertyChanged;

        void OnPropertyChanged([CallerMemberName]string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        string mCurrentCount;

        public void UpdateCounters(int i = 0)
        {
            CurrentCount = i.ToString();
        }

    }
}

MainWindow代码隐藏在后面

        public MainWindow()
        {
            InitializeComponent();
            CounterBtn.DataContext = cntMdl;
        }

        CounterModel cntMdl = new CounterModel();

CounterWindow代码背后:

        public CounterWindow()
        {
            InitializeComponent();
            DataContext = new CounterModel();
        }

CounterWindow Xaml

<TextBlock Text="{Binding CurrentCount}" FontSize="900" HorizontalAlignment="Center" VerticalAlignment="Center" FontFamily="Consolas" Foreground="White" MouseDown="TextBlock_MouseDown"/>

我想念什么?

1 个答案:

答案 0 :(得分:0)

不要为CounterWindow创建新的CounterModel实例。删除

DataContext = new CounterModel();

来自CounterWindow构造函数。

如果您正在从Button的Click事件处理程序中显示CounterWindow,请将当前DataContext传递到新窗口:

private void Button_Click(object sender, RoutedEventArgs e)
{
    var button = (Button)sender;
    var window = new CounterWindow { DataContext = button.DataContext };
    window.Show();
}
相关问题