【问题标题】:Boolean to Visibility Converter - inverted?布尔到可见性转换器 - 反转?
【发布时间】:2014-03-23 22:43:45
【问题描述】:

我该怎么做这样的事情

<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 中编写完整的方法来实现它? 或者我应该让这些图像重叠并在需要时隐藏一个?

【问题讨论】:

标签: c# wpf xaml converters


【解决方案1】:

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

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 并对其做出反应。

【讨论】:

  • 感谢您的回复。这是正确的,所以我已将其标记为正确。可惜没有这样的动作的内置参数。感谢您的回复。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2019-12-18
    • 2013-08-18
    • 2019-01-03
    • 2011-09-24
    • 2012-10-10
    • 1970-01-01
    • 2011-06-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多