托馬斯的答案工作正常,但你甚至不需要額外的依賴屬性。如果您有從ToggleButton繼承的類,則您的按鈕將正確更新,因此您可以重寫OnToggle方法,並更改ViewModel上的IsChecked綁定屬性。
的XAML:
<myControls:OneWayFromSourceToTargetToggle x:Name="MyCustomToggleButton"
Command="{Binding Path=ToggleDoStuffCommand}"
CommandParameter="{Binding RelativeSource={RelativeSource Mode=Self}}"
IsChecked="{Binding Path=ToggleIsCheckedConditionVar,
Mode=OneWay}"
/>
添加切換按鈕類:
public class OneWayFromSourceToTargetToggle : ToggleButton
{
/// <summary>
/// Overrides the OnToggle method, so it does not set the IsChecked Property automatically
/// </summary>
protected override void OnToggle()
{
// do nothing
}
}
然後在視圖模型只設置布爾ToggleIsCheckedCondition爲true或false。這是一個很好的方法,因爲您遵循了良好的MVVM實踐。
視圖模型:
public bool ToggleIsCheckedCondition
{
get { return _toggleIsCheckedCondition; }
set
{
if (_toggleIsCheckedCondition != value)
{
_toggleIsCheckedCondition = value;
NotifyPropertyChanged("ToggleIsCheckedCondition");
}
}
}
public ICommand ToggleDoStuffCommand
{
get {
return _toggleDoStuffCommand ??
(_toggleDoStuffCommand = new RelayCommand(ExecuteToggleDoStuffCommand));
}
}
private void ExecuteToggleDoStuffCommand(object param)
{
var btn = param as ToggleButton;
if (btn?.IsChecked == null)
{
return;
}
// has not been updated yet at this point
ToggleIsCheckedCondition = btn.IsChecked == false;
// do stuff
}
}
感謝。我會試一試。 – 2010-03-31 15:19:02
偉大的解決方案。 – Ross 2012-06-13 13:41:39