首页 > 解决方案 > 如何有效地处理多个按钮和其他元素的可见性和 isEnabled

问题描述

我的主过滤器上有一些元素,在我的 wpf 应用程序中。但是我不想在get/set中一一设置可见性和isEnabled。有没有更优雅的方法,如何从视图模型中改变它?谢谢!:)

标签: c#mvvm

解决方案


您可以使用 a根据视图模型属性DataTrigger更改您的某些属性:Button

<Window.Resources>
    <local:MyViewModel x:Key="viewModelInstance"></local:MyViewModel>
</Window.Resources>
<StackPanel>
    <Button DataContext="{StaticResource viewModelInstance}" Content="My Button">
        <Button.Style>
            <Style TargetType="Button">
                <!-- Default style is Visible and Enabled -->
                <Setter Property="IsEnabled" Value="True"></Setter>
                <Setter Property="Visibility" Value="Visible"></Setter>
                <Style.Triggers>
                    <DataTrigger Binding="{Binding IsAllowed}" Value="False">
                        <!-- Hide and disable when IsAllowed is false -->
                        <Setter Property="IsEnabled" Value="False"></Setter>
                        <Setter Property="Visibility" Value="Hidden"></Setter>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Button.Style>
    </Button>
</StackPanel>

假设您定义了一个视图模型类,如下所示:

public class MyViewModel : INotifyPropertyChanged {
    public bool IsAllowed { get; set; } = true;
    //Put more logic here of course.
}

MyViewModel应该实现INotifyPropertyChanged在属性更改时自动通知 UI 更新视图IsAllowed,例如:

public class MyViewModel : INotifyPropertyChanged {
    //Backing field for IsAllowed
    private bool _isAllowed = true;

    /// <summary>
    /// Gets or sets the IsAllowed property.
    /// </summary>
    public bool IsAllowed {
        get => _isAllowed; set {
            if (_isAllowed != value) {
                _isAllowed = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IsAllowed)));
            }
        }
    }
    //INotifyPropertyChanged
    public event PropertyChangedEventHandler PropertyChanged;
}

您还可以通过IValueCOnverter其他方式查看接口和 XAML 转换器。


推荐阅读