xaml - 将 IsVisible 绑定(bind)到由 Switch 切换的属性

标签 xaml xamarin.forms

我有一个 Switch 绑定(bind)到列表中元素的属性。我想将按钮的 IsVisible 绑定(bind)到同一属性,但当属性由 Switch 更改时,按钮的可见性不会更改。我错过了什么?

XAML:

<StackLayout>
    <ListView HorizontalOptions="FillAndExpand" ItemsSource="{Binding EquipmentList}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <StackLayout Orientation="Horizontal">
                        <Label Text="{Binding Name}" />
                        <Switch IsToggled="{Binding State}" />
                        <Button
                            Command="{Binding BindingContext.DoCommand, Source={x:Reference TestPage}}"
                            CommandParameter="{Binding .}"
                            IsVisible="{Binding State}"
                            Text="Click" />
                    </StackLayout>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</StackLayout>

View 模型:

private Command<Equipment> _doCommand;
    public Command<Equipment> DoCommand => _doCommand ??
(_doCommand = new Command<Equipment>((Equipment obj) => HandleEquipment(obj)));


// Outputs correct Name and State of the list item
private void HandleEquipment(Equipment obj)
{
        System.Diagnostics.Debug.WriteLine(obj.Name + ", " + obj.State);
}

型号:

class Equipment
{
    public int Id { get; set; }
    public string Name { get; set; }
    public bool State { get; set; }

    public Equipment(int Id, string Name, bool State)
    {
        this.Id = Id;
        this.Name = Name;
        this.State = State;
    }
}

最佳答案

正如 Gerald 在他的第一条评论中所写:您必须在 Equipment 模型上(而不仅仅是在 ViewModel 中)实现 INotifyPropertyChanged 接口(interface)。

如果没有这种实现, View 中的元素就没有机会知道状态发生了变化(在您的例子中是按钮)。

实现:

public class Equipment: INotifyPropertyChanged
{
    public bool State
    {
        get => _state;
        set =>
        {
            _state = value;
            OnPropertyChanged();
        }
    }
    private bool _state;

    // OTHER PROPERTIES

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged([CallerMemberName] string propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

方法OnPropertyChanged()的调用很重要。按钮的 IsVisible 属性会识别更改并更新其值。

关于xaml - 将 IsVisible 绑定(bind)到由 Switch 切换的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53335995/

相关文章:

c# - 如何在 UWP 应用程序中为椭圆的宽度和高度设置动画

c# - Pivot SelectedItem 属性导致 Windows UWP 崩溃

c# - XAML:命名空间奇怪的行为 Visual Studio

Android Activity 标签 android :name MD5 changed in Manifest file without changing any code

android - 检测移动应用程序是否是从 AppStore/Play Store 中的 Production Track 或 Beta Track 安装的

android - 推送通知使用负载打开正确的页面

c# - 旋转 slider WPF

c# - 更改 XAML 中的绑定(bind)值

Xamarin Forms Maps - 如何刷新/更新 map - CustomMap Renderer

xaml - 文本与 Xamarin Forms 中的链接按钮对齐