1

我该怎么做这样的事情

<BooleanToVisibilityConverter x:Key="BoolToVis"/>

<WrapPanel>
     <TextBlock Text="{Binding ElementName=ConnectionInformation_ServerName,Path=Text}"/>
     <Image Source="Images/Icons/Select.ico" Margin="2" Height="15" Visibility="{Binding SQLConnected,Converter={StaticResource BoolToVis},ConverterParameter=true}"/>
     <Image Source="Images/Icons/alarm private.ico" Margin="2" Height="15" Visibility="{Binding SQLConnected,Converter={StaticResource BoolToVis},ConverterParameter=false}"/>
</WrapPanel>

有没有办法使用 Boolean to vis 转换器但无需在 C 中编写完整的方法来实现它?或者我应该让这些图像重叠并在需要时隐藏一个?

4

2 回答 2

7

据我所知,您必须为此编写自己的实现。这是我使用的:

public class BooleanToVisibilityConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        bool boolValue = (bool)value;
        boolValue = (parameter != null) ? !boolValue : boolValue;
        return boolValue ? Visibility.Visible : Visibility.Collapsed;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

而且我通常设置ConverterParameter='negate',以便在代码中清楚参数在做什么。不指定 ConverterParameter 会使转换器的行为类似于内置的 BooleanToVisibilityConverter。如果您希望您的用法正常工作,您当然可以解析 ConverterParameterbool.TryParse()并对其做出反应。

于 2014-02-22T07:12:35.650 回答
1

来自@K Mehta ( https://stackoverflow.com/a/21951103/1963978 ),对 Windows 10 通用应用程序的方法签名进行了轻微更新(从“CultureInfo 文化”更改为“字符串语言”,每个https:// msdn.microsoft.com/en-us/library/windows/apps/xaml/hh701934.aspx):

public class BooleanToVisibilityConverter : IValueConverter
{
    public object Convert(object value, Type targetType,
        object parameter, string language)
    {
        bool boolValue = (bool)value;
        boolValue = (parameter != null) ? !boolValue : boolValue;
        return boolValue ? Visibility.Visible : Visibility.Collapsed;
    }

    public object ConvertBack(object value, Type targetType,
        object parameter, string language)
    {
        throw new NotImplementedException();
    }
}
于 2015-07-16T17:54:57.683 回答