Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change ToggleButton from ViewModel?

I came across an interesting issue.

Summary: I can't change the state of a toggle button from the ViewModel. The same problem seems to be with Microsoft ToggleButton as well as Telerik Controls.

ViewModel:

private bool? _isToggleChecked;
public bool? IsToggleChecked
{
    get { return _isToggleChecked; }
    set
    {
        if(_isToggleChecked == value)
            return;
        _isToggleChecked = value;
        RaisePropertyChanged(()=>IsToggleChecked);
    }
}

public VM()
{
    FireCommand = new DelegateCommand(OnFire);
}

private void OnFire()
{
    if (IsToggleChecked == null)
    {
        IsToggleChecked = true;
        return;
    }

    IsToggleChecked = !IsToggleChecked;
}

public DelegateCommand FireCommand { get; set; }

View: (Microsoft ToggleButton could be used instead with the same behavior)

<Grid x:Name="LayoutRoot" Background="White">
    <StackPanel>
        <telerik:RadToggleButton Height="50" IsChecked="{Binding IsToggleChecked}" />
        <Button Command="{Binding FireCommand}" Height="20" />
    </StackPanel>        
</Grid>

View Code Behind:

public MainPage()
{
    InitializeComponent();
    DataContext = new VM();
}

How is this possible? How can I change the toggle state programmaticaly?

Many Thanks,

like image 422
Houman Avatar asked Dec 04 '25 01:12

Houman


2 Answers

I had a problem with binding IsChecked on a RadRibbonToggleButton when I had the button bound to a command.

The workaround I found was to use a two way binding, but prevent the binding updating the source by using UpdateSourceTrigger=Explicit

IsChecked="{Binding IsLocked, Mode=TwoWay, UpdateSourceTrigger=Explicit}"

This works for me.

It is described as a known issue in WPF here

like image 111
TrystanC Avatar answered Dec 06 '25 14:12

TrystanC


To me this is a Nullable property problem, that telerik control doesn't support for some reason. If so, check on provider's site for available solutions/ service packs or simply make your property NON Nullable and refactor your code.

Regards.

like image 37
Tigran Avatar answered Dec 06 '25 14:12

Tigran



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!