2012-04-26 138 views
1

使用galasoft mvvm模板的wpf相当新颖。 我有两个继电器命令做同样的事情,但他们需要设置不同的属性。我可以通过属性名称设置属性吗?

我可以这样做吗?

public RelayCommand OpenDestinationCommand { get; private set; } 
public RelayCommand OpenSourceCommand { get; private set; } 

public MainViewModel(IDataService dataService) 
{ 
    OpenSourceCommand = new RelayCommand(() => GetPath(SourcePathPropertyName)); 
    OpenDestinationCommand = new RelayCommand(() => GetPath(DestinationPathPropertyName)); 
} 

private void GetPath(string PropertyName) { 
    //show a dialog, get the path they select 
    string newPath = GetPathFromDialog(); 
    //what should this look like? Is this possible? 
    var Property = GetPropertyByName(PropertyName); 
    Property.Set(newPath); 
} 

回答

1

应该首先使用Google搜索。改编自 http://geekswithblogs.net/shahed/archive/2006/11/19/97548.aspx

private PropertyInfo GetPropertyByName(string propName) 
{ 
    return this.GetType().GetProperty(propName); 
} 

private void GetPath(string PropertyName) { 
    //show a dialog, get the path they select 
    string newPath = GetPathFromDialog(); 
    //what should this look like? Is this possible? 
    var mProp = GetPropertyByName(PropertyName); 
    mPropp.SetValue(this, newPath, null); 
} 
+2

旁白:反思是*相对*慢 - 这将是罚款,只要它不是在一个紧密的循环或热路径。如果是:有更快的选择 - 让我知道你是否需要这个。 – 2012-04-26 21:32:31

+0

如果你有更好的答案,请使用它!不要花太多时间,perf在这里绝对不是问题。 – scaryman 2012-04-26 21:34:52

+0

我大多很好奇,如果有内置的WPF和/或mvvm灯。当我发布这个问题时,我完全划入并忘记了反思。 – scaryman 2012-04-26 21:35:35

相关问题