切换按钮的IsChecked属性没有遵循绑定的属性值

3

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

  <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。如果当前状态为启用,则会防止按钮点击发生。


这个控件的使用场景是什么?从你提供的信息来看,似乎是启动/停止服务器。我还有一些想法,但我不想再提供错误的建议了。 - Richard Preziosi
4个回答

0

就我个人而言,这是我所做的...看起来非常笨重。

我将绑定模式设置为TwoWay。似乎OneWay绑定不尊重IsChecked属性。

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

其次,我将IsButtonChecked的变异器属性no-opp了。
 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不尊重绑定属性...


0

你的绑定模式被设置为 OneWay,请将其设置为 TwoWay

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

你能发布一下你的ViewModel吗?我刚刚又读了一遍你发布的内容,感觉还有其他问题。 - Richard Preziosi
更新了我的当前解决方案。每次我设置 OneWay 绑定时,当用户单击 ToggleButton 时,它都会变成未选中状态。唯一的方法是使用 TwoWay 绑定,并让 mutator 基本上什么都不做,这样当用户点击按钮时,状态就被维持下来了。 - cgatian
我看过这篇文章(https://dev59.com/gVPTa4cB1Zd3GeqPn_n0#4883037),里面有人建议创建一个单向绑定的切换按钮。但是这真的必要吗?好像这个应该直接就可以工作了。 - cgatian

0

如我在这里的回答中所解释的那样,只需在DoNothing命令的第一步操作中引发PropertyChanged事件以更新IsButtonChecked属性即可。采用这种方法,就不需要扭曲绑定的属性。

如果需要更多详细信息,请查看参考答案。添加此答案是为了完整性,以便将寻找此问题的人引导到可能更简洁的解决方案。


0

在它能够工作之前,你必须设置Mode=TwoWayUpdateSourceTrigger=PropertyChanged两个属性:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接