从 ViewModel 返回 bool 到 View 绑定

我想要一个按钮来更改标签的可见性,一旦我单击它。


xaml视图:


<local:ButtonRenderer Text="Connect" BackgroundColor="#6DCFF6" TextColor="White" Command="{Binding viewTemperature}" CornerRadius="10" WidthRequest="200" IsVisible="{Binding !isConnecting}"/>

<Label Text="PlaceholderText" TextDecorations="Underline" TextColor="White" Margin="0,5,0,0" HorizontalTextAlignment="Center" IsVisible="{Binding !isConnecting}"/>

视图模型


viewTemperature = new Command(async () =>

{

    isConnecting = true;

    await _navigation.PushModalAsync(new TemperaturePage());

}) ;


public bool isConnecting

{

    get

    {

        return _isConnecting;

    }

    set

    {

        _isConnecting = value;

        PropertyChanged?.Invoke(this, new 

        PropertyChangedEventArgs(_isConnecting.ToString()));

    }

}

我已经在代码中放置了断点,并且 isConnected 在我的视图模型中被更改为 true。但是,我的标签的可见性没有改变。我怀疑这PropertyChanged不应该改变布尔值?


慕尼黑的夜晚无繁华
浏览 91回答 2
2回答

沧海一幻觉

你不能这样做IsVisible="{Binding !isConnecting}",这是行不通的。您可以制作 InvertBoolConverter,或者更简单的选项是使用触发器。这是一个示例:<Label Text="PlaceholderText" TextDecorations="Underline" TextColor="White" Margin="0,5,0,0" HorizontalTextAlignment="Center"&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; IsVisible="{Binding isConnecting}">&nbsp; &nbsp; <Label.Triggers>&nbsp; &nbsp; &nbsp; &nbsp; <DataTrigger TargetType="Label" Binding="{Binding isConnecting}" Value="True">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Setter Property="IsVisible" Value="False" />&nbsp; &nbsp; &nbsp; &nbsp; </DataTrigger>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<DataTrigger TargetType="Label" Binding="{Binding isConnecting}" Value="False">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Setter Property="IsVisible" Value="True" />&nbsp; &nbsp; &nbsp; &nbsp; </DataTrigger>&nbsp; &nbsp; </Label.Triggers></Label>

BIG阳

您可以改进您的代码ViewModelpublic event PropertyChangedEventHandler PropertyChanged;protected virtual void NotifyPropertyChanged([CallerMemberName] string propertyName = ""){&nbsp; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));}private bool isconnecting ;public bool isConnecting{&nbsp; get&nbsp; {&nbsp; &nbsp; return isconnecting;&nbsp; }&nbsp; set&nbsp; {&nbsp; &nbsp; if (isconnecting != value)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; isconnecting = value;&nbsp; &nbsp; &nbsp; NotifyPropertyChanged();&nbsp; &nbsp; }&nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP