2014-02-22 49 views
0

我怎么做这样的事情布尔能见度转换

<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> 

有使用布尔值,可见光转换器,但没有倒在写C的整体方法来做到这一点的方法吗? 或我应该只是有这些图像重叠,当我需要时隐藏一个?

+0

你可以很容易地改变转换器接受布尔参数来指示它是做标准转换还是反转换。 – har07

回答

6

据我所知,你必须为此编写你自己的实现。下面是我用什么:

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类似。如果你想让你的使用起作用,你当然可以使用bool.TryParse()来解析ConverterParameter并对它做出反应。

+0

感谢您的回复。这是正确的,所以我已经标记为如此。它只是一个耻辱,没有一个内置的paramater这样的行动。感谢您的答复。 –

0

从@K梅塔(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(); 
    } 
} 
当然