Search code examples
c#wpfdata-binding

data doesn't update on all bindings


I have two Windows, my MainWindow and a CounterWindow; on the MainWindow is a button with a binding and on my CounterWindow is a label with the same binding

When data is retrieved, the Button does receive the new data, but the CounterWindow label doesn't update.

Note, it turns to 0 on initializing (so the Binding functions!(?))

    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 codehbehind:

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

        CounterModel cntMdl = new CounterModel();

CounterWindow CodeBehind:

        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"/>

what am I missing?


Solution

  • Do not create a new CounterModel instance for the CounterWindow. Remove

    DataContext = new CounterModel();
    

    from the CounterWindow constructor.

    In case you are showing the CounterWindow from the Button's Click event handler, pass the current DataContext to the new window:

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