【发布时间】:2016-05-11 05:04:21
【问题描述】:
我有UserControl。在里面我有Grid。对此Grid,我根据另一个控件的值设置Opacity,即0 或1。要设置它,我正在使用下一个转换器:
[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();
}
}
将布尔值转换为Opacity 的转换器。对我来说,这一切似乎都是正确的。
但是当我转到使用 UserControl 的页面设计器时,我看到了错误
InvalidOperationException:目标必须是布尔值 在 SizeStream.WPF.Converters.OpacityConverter.Convert(Object value, Type targetType, Object parameter, CultureInfoculture)
当我构建我的项目时,一切正常。但在设计师 - 不是。
重新启动 VS 2013 没有帮助。
为什么会出现这样的问题?谢谢
<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}"/>
从这个元素我得到Tag 值。
<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}}">
这里我用转换器
答案:
在 StackOverflow 用户的帮助下,我的最终代码如下所示:
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;
}
【问题讨论】:
-
可以发布您的 Xaml 吗?
-
@SamTheDev,添加了 xaml
-
你为什么使用可以为空的布尔值?
-
@ChrisF,因为当我尝试将
value转换为bool时出现错误The as operator must be used with a reference type or nullable type ('bool' is a non-nullable value type)
标签: c# wpf opacity ivalueconverter