Admiral Land
Admiral Land

Reputation: 2492

Disable CheckBox with conditions

I have CheckBox and two TimePicker controls. I want to make checkbox enable when difference of TimePicker2-TimePicker1 > 0. And disable it otherwise.

Can I make it in XAML?

Here the code:

<xctk:TimePicker Grid.Row="1" Grid.Column="0" Height="22" HorizontalAlignment="Stretch"
                                 Format="ShortTime" Margin="8,0,0,0"
                                 Value="{Binding ViewModel.StartTime,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                                 ></xctk:TimePicker>

<xctk:TimePicker Grid.Row="3" Grid.Column="0" Height="22" HorizontalAlignment="Stretch"
                                 Format="ShortTime"  Margin="8,0,0,0"
                                 Value="{Binding ViewModel.EndTime,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                                 ></xctk:TimePicker>
<CheckBox Grid.Row="4"
                      HorizontalAlignment="Left" VerticalAlignment="Center"
                      Margin="8,0,0,0" 
                     ??? IsEnabled="{Binding ElementName=}"
                      IsChecked="{Binding ViewModel.Date,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                      />

Upvotes: 0

Views: 357

Answers (1)

Baldrick
Baldrick

Reputation: 11840

In your ViewModel, create a getter-only property that represents the validity of the dates in a UI-independent way. Like bool AreTimesValid. In the getter for this property, evaluate the difference between the start and end times, and return true or false accordingly.

Raise a property changed notification for the AreTimesValid property every time the StartTime and EndTime properties change.

class YourViewModel : INotifyPropertyChanged
{
    public bool AreTimesValid
    {
        get
        {
            return StartTime < EndTime;
        }
    }

    public DateTime StartTime
    {
        get
        {
            return startTime;
        }

        set
        {
            startTime = value;
            NotifyPropertyChanged("StartTime");
            NotifyPropertyChanged("AreTimesValid");
        }
    }

    private DateTime startTime;

    public DateTime EndTime
    {
        get
        {
            return endTime;
        }

        set
        {
            endTime = value;
            NotifyPropertyChanged("EndTime");
            NotifyPropertyChanged("AreTimesValid");
        }
    }

    private DateTime startTime;
}

Bind your CheckBox IsEnabled property to ths AreTimesValid field.

<CheckBox Grid.Row="4"
    HorizontalAlignment="Left" VerticalAlignment="Center"
    Margin="8,0,0,0" 
    IsEnabled="{Binding ElementName=ViewModel.AreTimesValid}"/>

The alternative is to use a converter implementing IMultiValueConverter, and put the comparison logic in there. Then you can bind directly. But the first solution is simpler and clearer, in my opinion.

Upvotes: 2

Related Questions