Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF DataBinding not updating?

I have a project, where I bind a checkbox's IsChecked property with a get/set in the codebehind. However, when the application loads, it doesn't update, for some reason. Intrigued, I stripped it down to its basics, like this:

//using statements
namespace NS
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private bool _test;
        public bool Test
        {
            get { Console.WriteLine("Accessed!"); return _test; }
            set { Console.WriteLine("Changed!"); _test = value; }
        }
        public MainWindow()
        {
            InitializeComponent();
            Test = true;
        }
    }
}

XAML:

<Window x:Class="TheTestingProject_WPF_.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" DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Grid>
    <Viewbox>
        <CheckBox IsChecked="{Binding Path=Test, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
    </Viewbox>
</Grid>

And, lo and behold, when I set it to true, it did not update!

Anyone can come up with a fix, or explain why?

Thanks, it'd be appreciated.

like image 282
It'sNotALie. Avatar asked Feb 19 '13 19:02

It'sNotALie.


1 Answers

In order to support data binding, your data object must implement INotifyPropertyChanged

Also, it's always a good idea to Separate Data from Presentation

public class ViewModel: INotifyPropertyChanged
{
    private bool _test;
    public bool Test
    {  get { return _test; }
       set
       {
           _test = value;
           NotifyPropertyChanged("Test");
       }
    }

    public PropertyChangedEventHandler PropertyChanged;

    public void NotifyPropertyChanged(string propertyName)
    {
         if (PropertyChanged != null)
             PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

<Window x:Class="TheTestingProject_WPF_.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>
    <Viewbox>
        <CheckBox IsChecked="{Binding Path=Test, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
    </Viewbox>
</Grid>

Code Behind:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new ViewModel{Test = true};
    }
}
like image 103
Federico Berasategui Avatar answered Sep 29 '22 06:09

Federico Berasategui