如果绑定的布尔属性为 false,如何将 xaml 元素的 IsVisible 属性设置为 true?

fon*_*ane 1 .net c# xaml maui

我想知道如果绑定属性的布尔值为 false,是否或如何将 xaml 元素的 IsVisible 属性设置为 true?

根据布尔属性的值,我想有条件地在视图中渲染不同的元素。

这是我的代码:

<ContentPage ...
  x:Name="page">

  <ListView BindingContext="{x:Reference page}" ItemSource="digitalInputs">
    <ListView.ItemTemplate>
      <DataTemplate x:DataType="services:DigitalInput">
        <ViewCell>
          <HorizontalStackLayout>
            <!-- This seems to be working. Render a green ball, if boolean value is true -->
            <Image Source="ballgreen" IsVisible="{Binding value}"/>
            <!-- Doesn't work. I want to render a red ball if the boolean value is false. -->
            <Image Source="ballred" IsVisible="{Binding !value}"/>
            <Label Text="{Binding valueText}" />
          </HorizontalStackLayout>
        </ViewCell>
      </DataTemplate>
    </ListView.ItemTemplate>
  </ListView>
</ContentPage>
Run Code Online (Sandbox Code Playgroud)

我考虑过向 DigitalInput 类添加另一个布尔属性,并将其值设置为 的相反值value,但另一方面,我不想触及该类,因为它以 1:1 的方式模拟我从 Web 服务检索数据的方式。

我也想过添加一个转换器,但我不知道如何做BindingContext。我希望有人可以帮助我并为我阐明这个问题。

亲切的问候。

Ger*_*uis 12

正如您已经提到的那样,有多种方法可以做到这一点。最简单的方法是:向模型添加倒置属性。这不是最优雅的选择。

在 XAML 本身中,您不能有任何逻辑,因此该!运算符将不起作用。转换器确实是一条出路。

实现 InverseBoolConverter

要实现IValueConverter本例中您需要的东西,请创建一个实现此接口的类。当您这样做时,您需要实现一些方法。在这种情况下,这些非常简单,因为它只是反转布尔值。

然而,由于它是 XAML 并且全部基于字符串,为了使其真正坚如磐石,您可能需要考虑一些错误处理。在这种情况下,我将采取快乐的道路。下面是一个示例实现:

public class InverseBoolConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return !((bool)value);
    }
    
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return value;

        // Converting back rarely happens, a lot of the converters will throw an exception
        //throw new NotImplementedException();
    }
}
Run Code Online (Sandbox Code Playgroud)

这段代码取自这个SO问题

现在要在 XAML 中使用它,请执行以下操作:<Image Source="ballred" IsVisible="{Binding value, Converter={converters:InverseBoolConverter}}"/>

您需要将一个xmlns条目添加到页面的根目录,如下所示: xmlns:converters="clr-namespace:YourProject.Namespace"。确保与上面YourProject.Namespace的命名空间匹配InverseBoolConverter

使用 .NET MAUI 社区工具包

好消息是,您不需要做任何这些!.NET MAUI 社区工具包已内置此功能。您只需安装 NuGet 包,使用此转换器即可开始使用。

在此页面上查找相关文档。