ToggleButton未被绑定



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

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

IsButtonChecked = false

当我点击切换按钮时,iccommand正确地触发(绑定到RelayCommand),该命令为CanExecute返回false。WPF ToggleButton的状态现在是Checked=true,但是后台模型仍然是IsButtonChecked = false。为什么UI更新为已检查状态,即使绑定属性没有?

边注

我能够阻止UI更新的唯一方法是创建一个逆属性IsButtonNotChecked。然后将该属性绑定到XAML中的IsEnabled。这可以防止在当前状态为启用时发生按钮单击。

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

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

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

我设置绑定模式为two - way。单向绑定似乎不尊重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命令中的第一个动作。使用这种方法,不需要扭曲bound属性。

如果需要,请查看参考答案以了解更多细节。为了完整起见,添加了这个答案,以引导人们找到一个可能不那么笨拙的解决方案。

你必须同时设置Mode=TwoWayUpdateSourceTrigger=PropertyChanged才能工作:

<ToggleButton 
IsChecked="{Binding IsButtonChecked, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
/>

最新更新