我敢肯定有一个更好的方法来解决这个问题,但这是我想出的一个快速解决方案,似乎可行。
这是 XAML:
<Window x:Class="StackOverflow.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:StackOverflow"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<local:AllNoneCheckboxConverter x:Key="converter"/>
</Window.Resources>
<Grid>
<StackPanel>
<CheckBox x:Name="chk1" Content="1"/>
<CheckBox x:Name="chk2" Content="2"/>
<CheckBox x:Name="chk3" Content="3"/>
<CheckBox x:Name="all" Content="all">
<CheckBox.IsChecked>
<MultiBinding Converter="{StaticResource converter}">
<Binding ElementName="chk1" Path="IsChecked"/>
<Binding ElementName="chk2" Path="IsChecked"/>
<Binding ElementName="chk3" Path="IsChecked"/>
</MultiBinding>
</CheckBox.IsChecked>
</CheckBox>
</StackPanel>
</Grid>
</Window>
这里是 MultiValueConverter;
class AllNoneCheckboxConverter: IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
bool result = (bool)values[0];
for (int i = 0; i < values.Length; i++)
if (result != (bool)values[i])
return null;
return result;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
object[] result = new object[targetTypes.Length];
bool isChecked = (bool)value;
for (int i = 0; i < result.Length; i++)
if (isChecked)
result[i] = true;
else
result[i] = false;
return result;
}
}