如果使用Reflection
一个选项然后是你 您可以使用Reflection
在ViewModel中设置属性。
你的命令的执行方法将成为这样的事情:
this.GetType().GetProperty((string)CommandParameter).SetValue(this, null, new object[] {});
但是,如果你愿意,你在你的问题中提到的XAML路线,那么你可以创建TriggerAction
和使用,在EventTrigger
。下面是我的尝试:
public sealed class SetProperty : TriggerAction<FrameworkElement>
{
public static readonly DependencyProperty SourceProperty =
DependencyProperty.Register("Source", typeof (object), typeof (SetProperty), new PropertyMetadata(default(object)));
/// <summary>
/// Source is DataContext
/// </summary>
public object Source
{
get { return (object) GetValue(SourceProperty); }
set { SetValue(SourceProperty, value); }
}
public static readonly DependencyProperty PropertyNameProperty =
DependencyProperty.Register("PropertyName", typeof (string), typeof (SetProperty), new PropertyMetadata(default(string)));
/// <summary>
/// Name of the Property
/// </summary>
public string PropertyName
{
get { return (string) GetValue(PropertyNameProperty); }
set { SetValue(PropertyNameProperty, value); }
}
public static readonly DependencyProperty ValueProperty =
DependencyProperty.Register("Value", typeof (object), typeof (SetProperty), new PropertyMetadata(default(object)));
/// <summary>
/// Value to Set
/// </summary>
public object Value
{
get { return (object) GetValue(ValueProperty); }
set { SetValue(ValueProperty, value); }
}
protected override void Invoke(object parameter)
{
if (Source == null) return;
if (string.IsNullOrEmpty(PropertyName)) return;
Source.GetType().GetProperty(PropertyName).SetValue(Source, Value, new object[] {});
}
}
和XAML:
<Button Content="Reset">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<local:SetProperty Source="{Binding}" PropertyName="PropertyToSet" Value="{x:Null}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
如果你不喜欢思考的话,那么你可以在你的视图模型操作的字典:
_propertyResetters = new Dictionary<string, Action>
{
{"PropertyToSet",() => PropertyToSet = null}
};
而且,在你的Command Execute方法中,你可以通过做_propertyResetters[(string)CommandParameter]();
希望这可以帮助或给你一些想法。
而不是使用'if'为什么不使用'switch'。不知道你是否有可能要求。 – Sandesh
@ aks81我没有看到你回答的方式与我的问题有关吗?你建议使用另一个控制语句,而我试图避免使用它。 – Goran
使用反射不是您的选择吗? – sthotakura