Boolean to Visibility Converter

霸气de小男生 提交于 2019-12-18 09:37:32

问题


how do i do something like this

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

is there a way to use the Boolean to vis converter but inverted without writing a whole method in C to do it? or should i just have these images overlap and hide one when i need to ?


回答1:


As far as I know, you have to write your own implementation for this. Here's what I use:

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();
    }
}

And I generally set ConverterParameter='negate' so it's clear in code what the parameter is doing. Not specifying a ConverterParameter makes the converter behave like the built-in BooleanToVisibilityConverter. If you want your usage to work, you can, of course, parse the ConverterParameter using bool.TryParse() and react to it.




回答2:


From @K Mehta (https://stackoverflow.com/a/21951103/1963978), with slight updates for the method signature for Windows 10 Universal applications (Changing from "CultureInfo culture" to "string language", per 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();
    }
}


来源:https://stackoverflow.com/questions/21951023/boolean-to-visibility-converter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!