如何将一个控件绑定到另一个控件的相反值?

问题描述 投票:0回答:1

我有一个入口控件,我想将其设置为密码。我还有一个复选框控件,我想将其设置为显示密码复选框。我的 XAML 代码如下所示:

        <Entry Placeholder="Enter Password Viewing Password"
           Grid.Row="3"
           TextColor="White"
           x:Name="vwPasswrd"
           BindingContext="{x:Reference chkVwPasswdShow}"
           IsPassword="{Binding IsChecked}"
           Margin="20,0,0,0"/>

    <HorizontalStackLayout
        Grid.Row="3"
        Grid.Column="1"
        HorizontalOptions="Center">

        <CheckBox x:Name="chkVwPasswdShow"
                VerticalOptions="Center"/>
        
        <Label Text="Show Password"
               FontSize="Micro"
               VerticalOptions="Center"
               TextColor="White"/>
    </HorizontalStackLayout>

但是,按照此代码的方式,复选框未选中,当用户开始在输入控件中输入数据时,将显示实际文本。单击复选框后,文本将显示为密码点。

我想反过来做:

  1. 取消选中该复选框时,我希望文本显示为密码点。
  2. 选中该复选框后,我希望文本显示为纯文本。

看来我必须以相反的方式绑定它。我该怎么做?

c# xaml data-binding passwords
1个回答
0
投票

您可以使用 MAUI Community Toolkit 中的 InvertedBoolConverter 来实现此目的:

<!-- Add converter here -->
<ContentPage.Resources>
    <mct:InvertedBoolConverter x:Key="InvertedBoolConverter" />
</ContentPage.Resources>

<Grid>

    <!-- use it here: -->

    <Entry Placeholder="Enter Password Viewing Password"
           Grid.Row="3"
           TextColor="White"
           x:Name="vwPasswrd"
           BindingContext="{x:Reference chkVwPasswdShow}"
           IsPassword="{Binding IsChecked, Converter={StaticResource InvertedBoolConverter}}"
           Margin="20,0,0,0"/>

    <!-- ... -->

</Grid>
© www.soinside.com 2019 - 2024. All rights reserved.