【问题标题】:Toggling a bound radio button by code通过代码切换绑定的单选按钮
【发布时间】:2012-10-14 04:32:17
【问题描述】:

WPF / Caliburn 微相关问题。

我有 4 个单选按钮,我将 IsChecked 属性绑定到 ArrowType,它具有我创建的 LogicArrowEnum 枚举类型。

单选按钮使用转换器根据单击的按钮正确地将相关枚举分配给 ArrowType 属性。

XAML:

<Window.Resources>
    <my:EnumToBoolConverter x:Key="EBConverter"/>
</Window.Resources>

...

<RadioButton IsChecked="{Binding ArrowType,
                Converter={StaticResource EBConverter},
                ConverterParameter={x:Static my:LogicArrowEnum.ARROW}}" 
                         Name="LogicArrow" 
                         Style="{StaticResource {x:Type ToggleButton}}" 
                         Width="50" 
                <TextBlock Text="Arrow"/>
</RadioButton>
<RadioButton IsChecked="{Binding ArrowType,
                Converter={StaticResource EBConverter},
                ConverterParameter={x:Static my:LogicArrowEnum.ASSIGN}}" 
                Name="LogicAssign"
                Style="{StaticResource {x:Type ToggleButton}}"
                Width="50" 
                <TextBlock Text="Assign"/>
</RadioButton>
<RadioButton
                IsChecked="{Binding ArrowType,
                Converter={StaticResource EBConverter},
                ConverterParameter={x:Static my:LogicArrowEnum.IF}}" 
                Name="LogicIf"
                Style="{StaticResource {x:Type ToggleButton}}" 
                Width="50"
                <TextBlock Text="If" />

代码:

public class EnumToBoolConverter : IValueConverter
{
    public object Convert(object value,
        Type targetType, object parameter,
        System.Globalization.CultureInfo culture)
    {
        if (parameter.Equals(value))
            return true;
        else
            return false;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return parameter;
    }
}  

public enum LogicArrowEnum
{
    ARROW = 1,
    ASSIGN = 2,
    IF = 3,
    IF_ELSE = 4
}

public LogicArrowEnum ArrowType
{
    get { return arrowType; }
    set
    {
        arrowType = value;

        NotifyOfPropertyChange(() => ArrowType);
    }
}

代码运行良好 - 用户单击按钮,ArrowType 属性被正确绑定。

我也想让这项工作倒退。例如,如果我通过代码将 ArrowType 属性设置为 LogicArrowEnum.ASSIGN,则 UI 应显示“分配”按钮已被切换。由于某种原因,这不能按预期工作。在 property 的 set 方法中,每当我将 ArrowType 属性分配给任意枚举时,arrowType 的私有字段首先被分配为我想要的值,但是一旦代码到达 NotifyOfPropertyChange 方法,它就会进入再次使用 set 方法,但随后将 arrowType 私有字段重置为先前切换的按钮。

这是与 Caliburn Micro 相关的错误还是与 WPF 相关的错误?我该如何解决这个问题?

【问题讨论】:

    标签: c# .net wpf caliburn.micro


    【解决方案1】:

    与 Caliburn.Micro 无关。 看看这个:How to bind RadioButtons to an enum?

    从 Scott 的回答中获取一个转换器,它会正常工作。

    【讨论】:

    • 我试过这个,但我遇到了同样的问题。您确定与 Caliburn Micro 没有任何关系吗?由于 NotifyOfPropertyChange,属性的 setter 激活了两次。
    • 啊,没关系,我只是注意到您提到的名称与接受的回答者不同。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2023-03-20
    • 2011-05-11
    • 2017-01-19
    • 1970-01-01
    • 2021-10-26
    • 1970-01-01
    • 2012-12-19
    • 1970-01-01
    相关资源
    最近更新 更多