0
votes

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?

2

2 Answers

0
votes

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

0
votes

You're question doesn't specify if the booleans are needed or are only there to help you get the wanted behaviour.

So in case you don't need them, you could also go for a function, which unchecks the other button. This could be also used for more than 2 ToggleButtons.
If you can be certain there are no other coontrols than ToggleButtons, you could also go for a foreach loop without the type-check.

public void ToggleButtonChecked(object sender, RoutedEventArgs e)
    {
        ToggleButton btn = sender as ToggleButton;
        if (btn == null)
            return;
        Panel container = btn.Parent as Panel;
        if (container == null)
            return;

        for (int i = 0; i<container.Children.Count; i++)
        {
            if (container.Children[i].GetType() == typeof(ToggleButton))
            {
                ToggleButton item = (ToggleButton)container.Children[i];
                if (item != btn && item.IsChecked == true)
                    item.IsChecked = false;
            }
        }
    }

XAML

<ToggleButton x:Name="tb1" Checked="ToggleButtonChecked"/>