首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在XAML中将布尔值中的null返回到复选框状态转换器

在XAML中将布尔值中的null返回到复选框状态转换器
EN

Stack Overflow用户
提问于 2014-05-25 22:23:48
回答 1查看 3.1K关注 0票数 2

我有一个TaskStatus到布尔转换器,在XAML中实现IValueConverter接口,用于Windows (通用应用程序)。

我有三个任务状态,并使用IsThreeState="true“在复选框中启用了不确定状态。

现在,尽管IsChecked属性似乎是一个布尔值,但转换器总是将System.Boolean作为目标类型。无论我返回什么(例如null),总是将其转换为false,因此我无法在复选框中获得第三种状态。

是否有一种方法可以在我的转换器中指定TargetType,或者返回null,以便IsChecked获得null作为输入,从而显示第三种状态?

这是转换器:

代码语言:javascript
复制
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-复选框的代码

代码语言:javascript
复制
<CheckBox x:Name="CheckBoxTaskState" 
    IsThreeState="True"
    IsChecked="{Binding Status, 
                Converter={StaticResource TaskStatusToCheckBoxStateConverter}, 
                Mode=TwoWay}">
</CheckBox>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-06-05 21:28:30

根据这一点:此时不支持绑定到WinRT中的可空类型。对于一个没有文件的规则来说,这是怎么回事?现在你知道了。

从这个开始

代码语言:javascript
复制
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));
        }
    }
}

还有这个

代码语言:javascript
复制
<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>

可以在“输出”窗口中验证此错误。它是这样写的:

错误:转换器未能将“布尔值”类型的值转换为“IReference1<Boolean>'; BindingExpression: Path='State' DataItem='App4.MainPage'; target element is 'Windows.UI.Xaml.Controls.CheckBox' (Name='checkBox'); target property is 'IsChecked' (type 'IReference1”)。

我对此不满意。所以让我们用附加的属性来解决这个问题。

代码语言:javascript
复制
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;
    }
}

您的XAML只会像这样改变:

代码语言:javascript
复制
<CheckBox Content="Hello three-state"
          IsThreeState="True"
          local:NullableCheckbox.Enabled="true"
          local:NullableCheckbox.IsChecked="{Binding State, Mode=TwoWay}" />

普通的IsChecked属性并不重要,它将被附加的属性覆盖。你的视图模型可以保持不变。这是真正的魔法是吧?

祝你好运!

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23860522

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档