2
votes

I have a TaskStatus to Boolean converter that implements the IValueConverter interface in XAML for Windows Store Apps (universal apps).

I have three task states and I enabled the indeterminate state in a checkbox using IsThreeState="true".

Now although the IsChecked property seems to be a Boolean?, the converter always gets System.Boolean as target type. Whatever I return (null for example) always converts to false and therefore I can't get the third state in my checkbox.

Is there a way to either specify the TargetType in my converter or return a null so that IsChecked gets null as input and therefore shows the third state?

Here is the converter:

public class TaskStatusToCheckBoxStateConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        var taskStatus = (TaskStatus) value;
        switch (taskStatus)
        {
            case TaskStatus.Open:
                return false;
            case TaskStatus.InProgress:
                return null;
            case TaskStatus.Done:
                return true;
            default:
                throw new ArgumentOutOfRangeException();
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        var checkBoxState = (Boolean?) value;
        if (checkBoxState == null)
            return TaskStatus.InProgress;
        if (checkBoxState.Value)
            return TaskStatus.Done;
        return TaskStatus.Open;
    }
}

XAML-Code for the Checkbox

<CheckBox x:Name="CheckBoxTaskState" 
    IsThreeState="True"
    IsChecked="{Binding Status, 
                Converter={StaticResource TaskStatusToCheckBoxStateConverter}, 
                Mode=TwoWay}">
</CheckBox>
1
Try returning a Nullable<Boolean> instead of just null. (Note that Nullable is a struct and it will be boxed as an object. Thus, returning null is not the same as returning a Nullable.)user2819245
Doesn't work either. Same result unfortunately. Or maybe I did it wrong. I have now return new Nullable<Boolean>();. Is this what you mean?Stephan
I just checked with tri-state checkbox and a System.Windows.Data.IValueConverter (don't have VS2013/a WindowsStore project at hand) whose Convert method returns either null or new Nullable<bool>. Both variants worked like a charm. Did you try setting breakpoints in your Convert and ConvertBack methods to observe what values the binding and the converter are processing in particular?user2819245
Yep. I checked that. When the value is TaskStatus.InProgress then the code correctly goes into the appropriate switch case. The target type is always System.Boolean. ConvertBack works like a charm. Just Convert does not return the correct null value. I also tried the same in a WPF application and just like on your side it works as expected (both null and Nullable<bool>).Stephan
This is odd. I do not believe that CheckBox or bindings with converters are broken in WindowsStore apps. If you see ConvertBack doing its work properly while Convert seems not to work, i can only think of the following scenarios that could cause your problem: (1) Somewhere in code-behind or as part of a trigger definition in XAML, the value of the CheckBox property IsChecked or IsThreeState is changed under certain circumstances. (2) Your code has another two-way databinding with the IsChecked or IsThreeState property as its binding source which alters the property.user2819245

1 Answers

2
votes

According to [this][1]: Binding to nullable types in WinRT isn't supported at this time. How's that for an undocumented rule? Now you know.

Start with this

public sealed partial class MainPage : Page, INotifyPropertyChanged
{
    public MainPage()
    {
        this.InitializeComponent();
        this.DataContext = this;
    }

    private void NullButton_Click(object sender, RoutedEventArgs e)
    { this.State = null; }

    private void FalseButton_Click(object sender, RoutedEventArgs e)
    { this.State = false; }

    private void TrueButton_Click(object sender, RoutedEventArgs e)
    { this.State = true; }

    bool? _State = null;
    public bool? State { get { return _State; } set { SetProperty(ref _State, value); } }

    public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
    void SetProperty<T>(ref T storage, T value, [System.Runtime.CompilerServices.CallerMemberName] String propertyName = null)
    {
        if (!object.Equals(storage, value))
        {
            storage = value;
            if (PropertyChanged != null)
                PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
        }
    }
}

And this

<Grid x:Name="grid" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
        <StackPanel Orientation="Horizontal">
            <Button Click="TrueButton_Click" Content="True" />
            <Button Click="FalseButton_Click" Content="False" />
            <Button Click="NullButton_Click" Content="Null" />
        </StackPanel>
        <TextBlock Text="{Binding State}" />
        <CheckBox x:Name="checkBox"
                  Content="Hello three-state"
                  IsThreeState="True"
                  IsChecked="{Binding State, Mode=TwoWay}" />
    </StackPanel>
</Grid>

You can verify this error in your Output window. It reads something like this:

Error: Converter failed to convert value of type 'Boolean' to type 'IReference1<Boolean>'; BindingExpression: Path='State' DataItem='App4.MainPage'; target element is 'Windows.UI.Xaml.Controls.CheckBox' (Name='checkBox'); target property is 'IsChecked' (type 'IReference1').

I am not pleased with this. So let's work around it with an attached property.

public class NullableCheckbox : DependencyObject
{
    public static bool GetEnabled(DependencyObject obj)
    { return (bool)obj.GetValue(EnabledProperty); }
    public static void SetEnabled(DependencyObject obj, bool value)
    { obj.SetValue(EnabledProperty, value); }
    public static readonly DependencyProperty EnabledProperty =
        DependencyProperty.RegisterAttached("Enabled", typeof(bool), typeof(NullableCheckbox), new PropertyMetadata(false, EnabledChanged));
    private static void EnabledChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var checkbox = d as CheckBox;
        if ((bool)e.NewValue)
        {
            var binding = new Binding
            {
                Path = new PropertyPath("IsChecked"),
                Mode = BindingMode.TwoWay,
                Source = checkbox,
            };
            checkbox.SetBinding(NullableCheckbox.InternalStateProperty, binding);
        }
    }

    private static object GetInternalState(DependencyObject obj)
    { return (object)obj.GetValue(InternalStateProperty); }
    private static void SetInternalState(DependencyObject obj, object value)
    { obj.SetValue(InternalStateProperty, value); }
    private static readonly DependencyProperty InternalStateProperty =
        DependencyProperty.RegisterAttached("InternalState", typeof(object),
        typeof(NullableCheckbox), new PropertyMetadata(null, InternalStateChanged));
    private static void InternalStateChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    { SetIsChecked(d, (object)e.NewValue); }

    public static object GetIsChecked(DependencyObject obj)
    { return (object)obj.GetValue(IsCheckedProperty); }
    public static void SetIsChecked(DependencyObject obj, object value)
    { obj.SetValue(IsCheckedProperty, value); }
    public static readonly DependencyProperty IsCheckedProperty =
        DependencyProperty.RegisterAttached("IsChecked", typeof(object),
        typeof(NullableCheckbox), new PropertyMetadata(default(object), IsCheckedChanged));
    private static void IsCheckedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var checkbox = d as CheckBox;
        bool? newvalue = null;
        if (e.NewValue is bool?)
            newvalue = (bool?)e.NewValue;
        else if (e.NewValue != null)
        {
            bool newbool;
            if (!bool.TryParse(e.NewValue.ToString(), out newbool))
                return;
            newvalue = newbool;
        }
        if (!checkbox.IsChecked.Equals(newvalue))
            checkbox.IsChecked = newvalue;
    }
}

Your XAML would only change like this:

<CheckBox Content="Hello three-state"
          IsThreeState="True"
          local:NullableCheckbox.Enabled="true"
          local:NullableCheckbox.IsChecked="{Binding State, Mode=TwoWay}" />

The regular IsChecked property doesn't matter, it will be overwritten by the attached property. Your viewmodel can stay the same. It's real magic, huh?

Best of luck!