【问题标题】:ToggleButton IsChecked Not Adhering to Bound PropertyToggleButton IsChecked 不遵守绑定属性
【发布时间】:2015-07-23 18:54:24
【问题描述】:

所以我有一个切换按钮如下:

  <ToggleButton 
      IsChecked="{Binding IsButtonChecked, Mode=OneWay}"
      Command="{Binding DoNothing}"
      CommandParameter="{Binding ServerViewModel}"
      Content="Click Me!"></ToggleButton>

IsButtonChecked = false

的初始值

当我单击切换按钮时,ICommand 会正确触发(绑定到 RelayCommand)并且此命令为 CanExecute 返回 false。 WPF ToggleButton 的状态现在为 Checked=true,但支持的模型仍为 IsButtonChecked = false。为什么 UI 更新为选中状态,而绑定的属性没有?

旁注

我能够阻止 UI 更新的唯一方法是创建一个反向属性 IsButtonNotChecked。然后我将该属性绑定到 XAML 中的 IsEnabled。如果状态当前已启用,这将防止发生按钮点击。

【问题讨论】:

  • 这个控件的用例是什么?从您提供的内容看来,您正在启动/停止服务器。我还有一些想法,但我不想再提供一个不正确的想法。

标签: wpf wpf-controls


【解决方案1】:

您已将绑定模式设置为OneWay,请将其设置为TwoWay

<ToggleButton Command="{Binding DoNothing}"
              CommandParameter="{Binding ServerViewModel}"
              Content="Click Me!"
              IsChecked="{Binding IsButtonChecked,
                                  Mode=TwoWay}" />

【讨论】:

  • 您能否发布您的 ViewModel,我刚刚再次阅读了您发布的内容,我感觉正在发生其他事情。
  • 更新了我当前的解决方案。每次我设置 OneWay 绑定时,当用户单击它时,ToggleButton 都会变为未选中状态。我能够保持检查的唯一方法是使用 TwoWay 绑定并且让 mutator 基本上什么都不做,这样当用户单击按钮时,状态就会保持。
  • 我确实看到了这篇文章 (stackoverflow.com/a/4883037/684869),有人建议创建单向绑定切换按钮?这甚至有必要吗?看起来这应该是开箱即用的。
【解决方案2】:

不管它的价值,这就是我所做的......它看起来真的很笨重。

我将绑定模式设置为双向。看起来 OneWay 绑定不尊重 IsChecked 属性。

  <ToggleButton 
      IsChecked="{Binding IsButtonChecked, Mode=TwoWay}"
      Command="{Binding DoNothing}"
      CommandParameter="{Binding ServerViewModel}"
      Content="Click Me!"></ToggleButton>

其次,我没有操作 IsButtonChecked 的 mutator 属性。

 public bool IsButtonChecked
        {
            get
            {
                return _isButtonChecked;
            }
            set
            {
                // Prevents the IsButtonCheckedfrom incorrectly being set to a
                // enabled state, yet the model is false
                // IsButtonCheckeddoesn't seem to respect OneWay binding.               
            }
        }

然后在后面的代码中,我更新 _isButtonChecked 属性并调用 INotifyPropertyChanged 事件。

internal void ShouldBeChecked(bool isChecked)
{ 
_isButtonChecked = isChecked;
 OnPropertyChanged("IsButtonChecked"); 
}

虽然真的很笨重...奇怪的是 ToggleButton 不尊重绑定的属性...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-15
    • 2011-06-20
    • 1970-01-01
    • 2011-06-25
    • 1970-01-01
    • 2010-12-04
    • 1970-01-01
    • 2012-03-08
    相关资源
    最近更新 更多