我正在使用 MVVM 架构来开发 WPF 应用程序...
到目前为止,一切都很顺利。
我遇到了绑定(bind)可见性的问题。如果可以的话,我想尽量减少在后面的代码中编写代码,但如果这是必需的,那么我不介意这样做。
我有一个 View 模型。该模型公开了一个 bool 值和 2 个命令。连接命令、断开连接命令和 DeviceCurrentlyConnected Bool。
基本上我决定制作 2 个按钮,但按钮的可见性基于 bool 值。
所以我在这方面遇到了困难。我尝试了很长一段时间的带有触发器的样式。
<Button Visibility="Hidden" Content="{x:Static UIStrings:ClientStrings.DeviceBar_DisconnectCommandName}" VerticalAlignment="Center" HorizontalAlignment="Center" Height="{Binding ElementName=this.Content, Path=DesiredHeight}" Margin="10" Name="Disconnect" Command="{Binding DisconnectCurrentDeviceCommand}">
<Button.Style>
<Style TargetType="Button">
<Style.Triggers>
<DataTrigger Binding="{Binding DataCotext.DeviceConnected, RelativeSource={RelativeSource FindAncestor, AncestorType=UserControl}}" Value="True">
<Setter Property="Visibility" Value="Visible"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
我根本无法让样式发挥作用。
基本上我想要的功能是:
设备已连接 = false: 显示一个按钮,其中包含内容 Connect 和绑定(bind)到 ConnectCommand 的命令。
设备已连接 = true: 显示一个按钮,其中包含内容断开连接和绑定(bind)到 DisconnectCommand 的命令。
当前没有设备连接时显示并绑定(bind)到连接设备的按钮,以及当连接到断开连接命令的设备时显示并说出断开连接一词的按钮。
最佳答案
编写一个 bool 值到可见性转换器,然后在按钮上使用该转换器。 Five minute recipe for a decent BoolToVisibilityConverter是一篇关于创建/使用可见性转换器的好文章。
我过去所做的是使用 bool 到可见性转换器,并将按钮的 IsEnabled 属性作为参数传递给转换器。由于该按钮是通过 CanExecute 方法在模型中的命令禁用/启用的,因此您可以使用 IsEnabled 属性通过转换器设置按钮的可见性。
关于WPF 按钮可见性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3507707/