0

I'm trying to make a checkbox bind to a subclass of my ViewModel class (without much luck).

In my ViewModel class...

public class TestClass
{
   private bool _TestValue;
   public bool TestValue
   {
      get { return _TestValue; }
      set
      {
         _TestValue = value;
         System.Windows.MessageBox.Show("TestValue = " + _TestValue);
      }
   }
}
public TestClass TC;

In my ViewModel constructor...

TC = new TestClass();
TC.TestValue = false;

In my View...

<CheckBox IsChecked="{Binding Path=TC.TestValue, Mode=TwoWay}">Option 1</CheckBox>

My expectation is that when I toggle the checkbox I should see windows popping up that say "TestValue = True" or "TestValue = False", but that doesn't happen. What am I missing?

jbudreau
  • 1,287
  • 1
  • 10
  • 22
  • 1
    That isn't the recommended approach to achieve something like that. You should Implement `INotifyPropertyChanged` to `TestClass` and then handle that event in your ViewModel. The code that raises the MessageBox will be in this handler – Agustin Meriles Jun 07 '17 at 23:40
  • As @AgustinMeriles said, implement the `INotifyPropertyChanged` interface. Look up proper mvvm tutorials. There are tons online. You will only need to implement minor changes to your existing `TestClass`. Btw AFAIK, `System.Windows.MessageBox` doesn't work in WPF. I remember that we used to implement our own dialog controls for this. – jegtugado Jun 08 '17 at 00:58
  • @Ephraim What do you mean `System.Windows.MessageBox` doesn't work in WPF? It works fine, I used it many times for test purposes. – Maxim Jun 08 '17 at 03:23

1 Answers1

2

Turn your TC public field into property and your binding will work.

public TestClass TC { get; }

You can learn more about this behavior from this post.

Maxim
  • 1,995
  • 1
  • 19
  • 24