c# - 如何有效地处理多个按钮和其他元素的可见性和 isEnabled
问题描述
我的主过滤器上有一些元素,在我的 wpf 应用程序中。但是我不想在get/set中一一设置可见性和isEnabled。有没有更优雅的方法,如何从视图模型中改变它?谢谢!:)
解决方案
您可以使用 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 转换器。
推荐阅读
- azure - Mail.ReadBasic 等效应用范围
- typeorm - 找不到 Role#users 的实体元数据
- excel - 在工作簿之间移动工作表的问题
- bash - 创建存储帐户后无法立即创建 Azure 容器
- android - 如何在 NativeScript 中创建自定义导航栏?
- javascript - 用 3 个不同的按钮显示 3 个不同的表格
- javascript - 制作一个更改日志表,在下拉菜单中记录更改
- java - 初始化具有另一个类对象作为成员变量的类
- python-3.x - + 不支持的操作数类型:“_regex.Pattern”和“str”
- java - 如何更改 JTextField 的大小?