A.R. Lear A.R. Lear -4 years ago 215
C# Question

WPF ToggleButton Binding Not Working

I have two ToggleButtons; I'm trying to make them behave like a pair of radio buttons by binding them to booleans, but it's not working. Here's what I have so far:

<ToggleButton Name="YesButton" Margin="5,0" Width="100" IsChecked="{Binding YesBool, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">Yes!</ToggleButton>

<ToggleButton Name="NoButton" Margin="5,0" Width="100" IsChecked="{Binding NoBool, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">No!</ToggleButton>


And

public partial class MainWindow : Window
{
public MainWindow()
{
DataContext = this;
InitializeComponent();
}
}

public class Thingy : INotifyPropertyChanged
{
private bool _yesno;

public bool YesBool
{
get { return _yesno; }
set { _yesno = value; NotifyPropertyChanged("YesBool"); }
}

public bool NoBool
{
get { return !_yesno; }
set { _yesno = !value; NotifyPropertyChanged("NoBool"); }
}

public event PropertyChangedEventHandler PropertyChanged;

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


As far as I can tell, everyone else who had this problem misspelled their binding or didn't use NotifyPropertyChanged, but (as far as I can tell) I'm doing both of those things. What am I doing wrong?

Answer Source

Set your DataContext in your xaml to your Thingy class instead of "this" Window.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download