【问题标题】:Need to disable buttons on the window if several conditions are not met如果不满足几个条件,需要禁用窗口上的按钮
【发布时间】:2012-05-07 21:04:20
【问题描述】:

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

我的视图模型库中有两个类,分别称为DbMonitorComMonitor(“Com”代表“Communications”)。它们来自同一个抽象类,实现IPropertyChanged 接口,并有一个名为Status 的属性(继承自抽象基类),它是一个名为DeviceStatuses 的枚举,其值为GreenYellow、和Red。我希望仅当两个对象的状态属性均为Green 时才启用按钮?

如何让这个绑定在 Xaml 中工作,或者我必须在我的代码隐藏中这样做。

谢谢

托尼

【问题讨论】:

    标签: wpf data-binding binding


    【解决方案1】:

    您是否使用带有这些按钮的命令?如果不是,您切换到命令有多难? ICommandCanExecute 部分似乎是这里的路。

    【讨论】:

      【解决方案2】:

      有三种方法可以解决这个问题:
      1.使用 Converter 将按钮的 IsEnabled 属性绑定到您的 Status 属性,以从 DeviceStatus 映射到 bool(启用或未启用)。我不会推荐这个。
      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 逻辑。

      【讨论】:

        【解决方案3】:

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

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

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

        这很好用。

        此时我无法将按钮转换为使用 ICommand。在我们的发布日期之前没有足够的时间。

        托尼

        【讨论】:

        • 如果你想使用真正的 Viewmodel,你真的必须研究 Delegate/RelayCommand 的东西。让你的代码更容易
        • 您可以在 VM bool ButtonIsEnabled 中声明一个属性,并直接将其与 Button Property IsEnabled="{Binding ButtonIsEnabled}" 绑定,在 VM 中您可以根据您的条件将 ButtonIsEnabled 设置为 true 或 false。但是使用 ICommand 是可行的方法。
        猜你喜欢
        • 1970-01-01
        • 2021-09-11
        • 2021-09-24
        • 1970-01-01
        • 2019-07-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多