问题
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>
回答1:
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.
来源:https://stackoverflow.com/questions/6112857/handling-exclusive-or-conditions-when-binding-to-two-boolean-properties-in-xaml