我可以通过属性名称设置属性吗?

时间:2012-04-26 21:26:20

标签: c# mvvm properties

wpf相当新,使用galasoft mvvm模板。 我有两个执行相同操作的relay命令,但是它们需要设置不同的属性。

我可以这样做吗?

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 个答案:

答案 0 :(得分: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);
}