2012-04-26 137 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

相關問題