[英]What executes first: ToggleButton.IsChecked binding update, or Command binding?
First - a disclaimer: 首先 - 免责声明:
If you're reading this because you want to use both a binding for IsChecked and a RelayCommand to change things, you probably are doing it wrong.
如果您正在阅读此内容,因为您想同时使用IsChecked的绑定和RelayCommand来更改内容,那么您可能做错了。 You should be working off of the
IsChecked
binding'sSet()
call.您应该使用
IsChecked
绑定的Set()
调用。
The question: 问题:
I have a ToggleButton in which there's both a binding for IsChecked
and for a Command
: 我有一个ToggleButton,其中有
IsChecked
和Command
的绑定:
<ToggleButton IsChecked="{Binding BooleanBackedProperty}"
Command="{Binding SomeCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}"
CommandParameter="{Binding}" />
Yes - I know, tsk tsk. 是的 - 我知道,tsk tsk。 Couldn't be helped.
无法帮助。
When the user clicks the ToggleButton, which these two is going to fire first? 当用户点击ToggleButton时,这两个将首先触发? Is the Command going to be executed, or is the IsChecked binding going to update the bound property?
Command是否会被执行,或者IsChecked绑定是否会更新绑定属性? Or - is this actually similar to the post on social in which it creates a race condition ?
或者 - 这实际上类似于创造竞争条件的社交帖子吗?
IsChecked
will have a valid value at the command run time. IsChecked
在命令运行时将具有有效值。
ToggleButton
overrides OnClick
from ButtonBase
like this: ToggleButton
从ButtonBase
重写OnClick
,如下所示:
protected override void OnClick()
{
OnToggle();
base.OnClick();
}
OnToggle
is the method that updates IsChecked
: OnToggle
是更新IsChecked
的方法:
protected internal virtual void OnToggle()
{
// If IsChecked == true && IsThreeState == true ---> IsChecked = null
// If IsChecked == true && IsThreeState == false ---> IsChecked = false
// If IsChecked == false ---> IsChecked = true
// If IsChecked == null ---> IsChecked = false
bool? isChecked;
if (IsChecked == true)
isChecked = IsThreeState ? (bool?)null : (bool?)false;
else // false or null
isChecked = IsChecked.HasValue; // HasValue returns true if IsChecked==false
SetCurrentValueInternal(IsCheckedProperty, isChecked);
}
And the base OnClick
fires the command: 基础
OnClick
会触发命令:
protected virtual void OnClick()
{
RoutedEventArgs newEvent = new RoutedEventArgs(ButtonBase.ClickEvent, this);
RaiseEvent(newEvent);
MS.Internal.Commands.CommandHelpers.ExecuteCommandSource(this);
}
Source: MSDN Reference Source 来源: MSDN参考资料来源
So the value should be valid by the time the command runs. 因此,该值应在命令运行时有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.