Reputation: 6235
I have UserControl
. In it I have Grid
. To this Grid
I set Opacity
which is 0
or 1
according to value of another control. To set it I am using next converter :
[ValueConversion(typeof(bool), typeof(double))]
public class OpacityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var b = value as bool?;
if (targetType != typeof(bool) && !b.HasValue)
throw new InvalidOperationException("The target must be a boolean");
if (b.HasValue)
{
return b.Value ? 1 : 0;
}
return 0;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Converter which transform bool value into Opacity
. For me it all seems correct.
But when I go to designer of page where I use that UserControl
I see error
InvalidOperationException: The target must be a boolean at SizeStream.WPF.Converters.OpacityConverter.Convert(Object value, Type targetType, Object parameter, CultureInfo culture)
When I build my project everything is Ok. But In designer - not.
Restarting VS 2013 doesn't help.
Why there are such problem? Thanks
<controls:MultiSelectComboBox Tag="{Binding PanelLoading, Converter={StaticResource InverseConverter}}" SelectedItems="{Binding SelectedBrandsList, Mode=TwoWay}" Grid.Column="2" Grid.Row="0" x:Name="BrandsFilter" DefaultText="Brand" ItemsSource="{Binding BrandsList}" Style="{StaticResource FiltersDropDowns}"/>
From this element I get Tag
value.
<Grid Background="#FF826C83" Name="DropDown" SnapsToDevicePixels="True" MinWidth="{TemplateBinding ActualWidth}" MaxHeight="{TemplateBinding MaxDropDownHeight}" Opacity="{Binding Path=Tag, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}, Converter={StaticResource OpacityConverter}}">
Here I use converter
Answer :
With help of StackOverflow users my final code looks like :
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (targetType != typeof(double))
throw new InvalidOperationException("The target must be a double");
if (value is bool)
{
return (bool)value ? 1 : 0;
}
return 0;
}
Upvotes: 0
Views: 1170
Reputation: 432
if (targetType != typeof(bool) && !b.HasValue)
throw new InvalidOperationException("The target must be a boolean");
If you intend to convert from bool to double, then your target type must be checked against "double" in the above code.
Upvotes: 1