Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mutually Exclusive Checkboxes - C#, MVVM

I am writing a program which will have two possibilities: Set Time & Date Manually, or use Computer/System Time & Date.

So now I need to make two Checkboxes which are Mutually Exclusive. When one will be chosen, another must be Unchecked. How to do it this in MVVM?

<CheckBox Name="UseSystemTime" Margin="7"  Content="Use System Time and Date settings (Time, Date, DST, Timezone)" IsChecked="{Binding UseSystemTime}"/>
<CheckBox Name="ManualTime" Margin="7"  Content="Set settings Manually" IsChecked="{Binding SetSettingsManually}"/>

Is there a way to do this in XAML?

WPF coding mutually exclusive Checkboxes with Data Binding

Thanks!

like image 711
esispaned Avatar asked Mar 14 '26 04:03

esispaned


1 Answers

In your case of having only 2 checkboxes i would introduce only one bool-property in my viewmodel for the ManualTime like.

public bool IsManualTimeUsed
{
   // get;set with property-changed 
}

Then in the UI you have two opportunities:

Opportunity 1:

 <CheckBox Name="UseSystemTime" Margin="7" Content="Use System Time and Date settings (Time, Date, DST, Timezone)" 
           IsChecked="{Binding IsManualTimeUsed, Converter{converterNamespace:InverseBoolConverter}}"/>
 <CheckBox Name="ManualTime" Margin="7" Content="Set settings Manually" 
           IsChecked="{Binding IsManualTimeUsed}"/>

where the InverseBoolConverter can look like:

public class InverseBoolConverter : MarkupExtension, IValueConverter
{
    private static InverseBoolConverter converter;

    public InverseBoolConverter()
    {

    }

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is bool)
            return !((bool) value);
        return value;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        return converter ?? (converter = new InverseBoolConverter());
    }
}

Opportunity 2

<CheckBox Name="UseSystemTime" Margin="7" Content="Use System Time and Date settings (Time, Date, DST, Timezone)" 
          IsChecked="{Binding ElementName=ManualTime, Path=IsChecked, Converter={converterNamespace:InverseBoolConverter}}"/>
<CheckBox Name="ManualTime" Margin="7" Content="Set settings Manually" 
          IsChecked="{Binding IsManualTimeUsed}"/>

with the same converter as in opportunity 1

like image 96
Tomtom Avatar answered Mar 16 '26 18:03

Tomtom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!