Câu trả lời của Thomas hoạt động tốt, nhưng bạn thậm chí không cần thêm thuộc tính phụ thuộc. Nút của bạn sẽ cập nhật chính xác nếu bạn có lớp kế thừa từ ToggleButton để bạn có thể ghi đè lên phương thức OnToggle, và bạn thay đổi thuộc tính ràng buộc IsChecked trên ViewModel.
XAML:
<myControls:OneWayFromSourceToTargetToggle x:Name="MyCustomToggleButton"
Command="{Binding Path=ToggleDoStuffCommand}"
CommandParameter="{Binding RelativeSource={RelativeSource Mode=Self}}"
IsChecked="{Binding Path=ToggleIsCheckedConditionVar,
Mode=OneWay}"
/>
Added ToggleButton Class:
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
}
}
Sau đó, trong ViewModel chỉ cần đặt bool ToggleIsCheckedCondition là đúng hoặc sai. Đây là một cách hay để làm điều đó bởi vì bạn đang theo dõi các thực hành MVVM tốt.
ViewModel:
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
}
}
Nguồn
2017-02-10 18:43:26
Cảm ơn. Tôi sẽ thử. –
Giải pháp tuyệt vời. – Ross