且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在XAML绑定到两个布尔属性,当处理异或条件

更新时间:2023-10-06 13:38:58

我不认为你将能够做到这一点的直XAML。你将不得不在你的code-背后/视图模型要么写code或编写自定义的IValueConverter(可能是一个多转换?)来处理它。无论哪种方式,它的一些code。

So I have a class I want to bind to:

public class Awesome {
    public bool OptionA1 { get; set; }
    public bool OptionA2 { get; set; }

    public bool OptionB1 { get; set; }
    public bool OptionB2 { get; set; }
}

When I expose this class in my GUI, I have two radio buttons (called radioButtonA and radioButtonB) which let the user pick between groups A and B, and I have two checkboxes to let the user change A1/A2 and B1/B2 respectively depending on which radiobutton ischecked.

The logic in the class doesn't technically differentiate between A and B like I do on my GUI. So if OptionA1 == True and OptionB1 == True, the class will execute behaviour for OptionA1 and B1 as expected.

However, I want to expose groups A and B as exclusive-or: meaning that if OptionA1 or OptionA2 are set to true, OptionB1 and OptionB2 must both be false. And vice versa.

The following binding will automatically repurpose/rebind the checkbox depending on which radiobutton/group is checked, but it does not enforce the exclusive-or relationship between the groups. So, the user can click RadioButtonA and check both boxes. If the user then clicks RadioButtonB, OptionA1 and OptionA2 are still set to true (as expected). How do I automatically set them to false when RadioButtonB ischecked?

<CheckBox Content="Do Option 1">
    <CheckBox.Style>
        <Style TargetType="CheckBox">
            <Style.Triggers>
                <DataTrigger Binding="{Binding ElementName=radioButtonA, Path=IsChecked}" Value="True">
                    <Setter Property="IsChecked">
                        <Setter.Value>
                            <Binding Path="OptionA1" Mode="TwoWay"/>
                        </Setter.Value>
                    </Setter>
                </DataTrigger>
                <DataTrigger Binding="{Binding ElementName=radioButtonB, Path=IsChecked}" Value="True">
                    <Setter Property="IsChecked">
                        <Setter.Value>
                            <Binding Path="OptionB1" Mode="TwoWay"/>
                        </Setter.Value>
                    </Setter>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </CheckBox.Style>
</CheckBox>

I don't think you're going to be able to do this in straight XAML. You are going to have to either write code in your code-behind/viewmodel or write a custom IValueConverter (perhaps a MultiConverter?) that handles it. Either way, its some code.