繁体   English   中英

ToggleButton IsChecked 不遵守绑定属性

[英]ToggleButton IsChecked Not Adhering to Bound Property

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

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

IsButtonChecked 的初始值 = false

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

边注

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

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

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

对于它的价值,这就是我所做的。。它看起来确实很笨拙。

我将绑定模式设置为TwoWay。 看起来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不尊重绑定属性,这很奇怪。

正如我在此处的回答中所解释的,只需将IsButtonChecked属性的PropertyChanged事件作为DoNothing命令中的第一个操作。 使用这种方法不需要扭曲绑定属性。

如果需要,请查看参考答案以获取更多详细信息。 为了完整性而添加了这个答案,以引导人们找到这个问题,找到一个可能不那么笨拙的解决方案。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM