如果不满足几个条件,则需要禁用窗口上的按钮



我的WPF应用程序在其主窗口中有许多按钮。 我现在正在处理一种边缘情况,如果数据库关闭或应用程序无法与其后端建立连接(后端是我们编写的 Windows 服务),则应禁用按钮。

在我的视图模型库中有两个类,分别称为DbMonitorComMonitor("Com"表示"通信")。 它们来自同一个抽象类,实现IPropertyChanged接口,并具有一个名为 Status 的属性(继承自抽象基类),该属性是名为 DeviceStatuses 的枚举,其值为 GreenYellowRed。 我希望仅当两个对象的 Status 属性都Green

如何让此绑定在 Xaml 中工作,还是必须在代码隐藏中执行此操作。

谢谢

托尼

您是否将这些按钮一起使用命令?如果没有,切换到命令有多难?ICommand CanExecute部分似乎是要走的路。

有三种方法可以做到这一点:
1. 使用转换器将按钮的 IsEnabled 属性绑定到您的状态属性,以从设备状态映射到布尔值(启用与否)。 我不推荐这个。
2. 路由命令

public static RoutedCommand MyButtonCommand = new RoutedCommand();
private void CommandBinding_MyButtonEnabled(object sender, CanExecuteRoutedEventArgs e) {
    e.CanExecute = Db.Monitor.Status==DeviceStatuses.Green;
}

并在 XAML 中绑定到它:

<Window.CommandBindings>
<CommandBinding
    Command="{x:Static p:Window1.MyButtonCommand}"
    Executed="buttonMyButton_Executed"
    CanExecute="CommandBinding_MyButtonEnabled" />
</Window.CommandBindings>  
<Button Content="My Button" Command="{x:Static p:Window1.MyButtonCommand}"/>

3. 实施 ICommand

public class MyCmd : ICommand {
    public virtual bool CanExecute(object parameter) {
        return Db.Monitor.Status==DeviceStatuses.Green;
    }
}

此处的命令是相应视图模型的属性:

class MyViewModel {
    public MyCmd myCcmd { get; set; }
}

并在 XAML 中绑定到它:

<Button Content="My Button" Command="{Binding myCmd}"/>

第三种方法通常是最灵活的。 您需要将具有状态属性的视图模型注入到 Command 构造函数中,以便实现 CanExecute 逻辑。

在提出这个问题后,我做了一些额外的研究,并找到了适合我的解决方案。

我创建了一个实现 IMultiConverter 接口的类,该接口将我的DeviceStatuses枚举转换为布尔值。 然后,在我的 Xaml 中,我这样做了:

<Button ....>
    <Button.IsEnabled>
        <MultiBinding Converter="{StaticResource DeviceStatusToBool}">
            <Binding Path="..." />
            <Binding Path="..." />
        </MuntiBinding>
    </Button.IsEnabled>
</Button>

这效果很好。

此时我无法将按钮转换为使用 ICommand。 距离我们的发布日期还不够。

托尼

最新更新