थॉमस का उत्तर ठीक काम करता है, लेकिन आपको अतिरिक्त निर्भरता संपत्ति की भी आवश्यकता नहीं है। यदि आपके पास ToggleButton से क्लास का उत्तराधिकारी है तो आपका बटन सही तरीके से अपडेट हो जाएगा ताकि आप ऑनटॉगल विधि को ओवरराइड कर सकें, और आप ViewModel पर Ischecked bound property को बदल सकते हैं।
Xaml:
<myControls:OneWayFromSourceToTargetToggle x:Name="MyCustomToggleButton"
Command="{Binding Path=ToggleDoStuffCommand}"
CommandParameter="{Binding RelativeSource={RelativeSource Mode=Self}}"
IsChecked="{Binding Path=ToggleIsCheckedConditionVar,
Mode=OneWay}"
/>
जोड़ा गया ToggleButton कक्षा:
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
}
}
तो सही या गलत का ViewModel सिर्फ सेट bool ToggleIsCheckedCondition में
। ऐसा करने का यह एक अच्छा तरीका है क्योंकि आप अच्छे एमवीवीएम प्रथाओं का पालन कर रहे हैं।
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
}
}
स्रोत
2017-02-10 18:43:26
धन्यवाद। मैं इसे आज़मा दूंगा। –
ग्रेट समाधान। – Ross