I have two ToggleButtons
.
I need to bind one IsChecked
property to the other ToggleButton
.
I use a custom Converter
to inverse the value.
However, it's not working? Here's my code:
XAML:
<ToggleButton
IsChecked="{Binding Path=ToggleButton.IsChecked, ElementName=menuCatUit,
Converter={StaticResource InvertBool}}"/>
<ToggleButton x:Name="menuCatUit" IsChecked="True" />
Code:
[ValueConversion(typeof(bool), typeof(bool))]
public class InverseBooleanConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (targetType != typeof(bool))
throw new InvalidOperationException("The target must be a boolean");
return !(bool)value;
}
}
Remove the "ToggleButton" from the path property.
You only need the property name.
<ToggleButton
IsChecked="{Binding Path=IsChecked, ElementName=menuCatUit,
Converter={StaticResource InvertBool}}"/>
Here is what i Do, I send them all to the same Checked and UnChecked event:
privateToggleButton Toggle;
public void ToggleButtonChecked(object sender, RoutedEventArgs e)
{
if (Toggle != null && Toggle != sender as ToggleButton)
{
Toggle.IsChecked = false;
}
Toggle = sender as ToggleButton;
}
public void ToggleButtonUnChecked(object sender, RoutedEventArgs e)
{
if (Toggle != null)
{
Toggle = null;
}
}
And then to check which ToggleButton is checked do something like this
switch (Toggle.Name)
{
case ("Button1"): /*MyCode*/ break;
};
Found the solution:
I needed to edit my converter
because ToggleButton
uses a nullable bool
.
[ValueConversion(typeof(bool?), typeof(bool))]
public class InverseNullableBool : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (targetType != typeof(bool?))
throw new InvalidOperationException("The target must be a nullable boolean");
bool? b = (bool?)value;
return !(b.HasValue && b.Value);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.