对于涉及Person对象的PersonName的六个组件的演示文稿,我添加了一个扩展名和一个“迷你视图模型”(PersonNamePropertyTextBox)来减少重复的代码并促进数据绑定。我可以在没有反射的情况下做到这一点吗?
所以在父视图模型的构造,我创建这些迷你视图模型,如:
public PimDetailVm(Person person, ..)
{
LastName = new PersonNamePropertyTextBox(
() => Model.GetPersonName().LastName, v => this.UpdatePersonNameProperty(pn => pn.LastName, v))
{
Label = PeopleResources.LastName_Label
};
FirstName = new PersonNamePropertyTextBox(
() => Model.GetPersonName().FirstName, v => this.UpdatePersonNameProperty(pn => pn.FirstName, v))
{
Label = PeopleResources.FirstName_Label
};
... etc.
}
public PersonNamePropertyTextBox LastName { get; private set; }
public PersonNamePropertyTextBox FirstName { get; private set; }
什么,我会真的像现在是能够做的仅仅是通过在当前属性,即“姓”和标签值,并让迷你视图模型设置相应的getter/setter的代表,是这样的:
LastName = new PersonNamePropertyTextBox(vm=>LastName, PeopleResources.LastName_Label);
我奋力至于如何做到这一点,虽然。有任何想法吗?
扩展(处理更新PERSONNAME在Model)
public static void UpdatePersonNameProperty(this PimDetailVm vm, Expression<Func<PersonName, object>> propertyExpression, string value)
{
var pn = vm.Model.GetPersonName();
var pnProps = pn.GetType().GetProperties();
var subj = ExprHelper.GetPropertyName(propertyExpression);
var subjProp = pnProps.Single(pi => pi.Name.Equals(subj));
var currentVal = subjProp.GetValue(pn, null);
// split if there is nothing to update
if(currentVal==null && value==null) return;
if (currentVal != null && currentVal.Equals(value)) return;
// update the property
var capitalized = value == null ? null : value.Capitalize();
subjProp.SetValue(pn, capitalized, null);
// update the model
vm.Model.SetName(pn);
// broadcast the update
vm.NotifyOfPropertyChange(subj, value);
}
迷你视图模型的PERSONNAME
public class PersonNamePropertyTextBox : TextBoxActionData
{
public PersonNamePropertyTextBox(Func<string> getterFunc, Action<string> setterAction) {
if (getterFunc == null) throw new ArgumentNullException("getterFunc");
if (setterAction == null) throw new ArgumentNullException("setterAction");
GetterFunc = getterFunc;
SetterAction = setterAction;
}
}
为什么你想避免反思? – CodesInChaos
@CodeInChaos:有趣的问题,我尽量避免反射,大致像交通堵塞。我不喜欢在繁忙的交通中开车,但有时你只需... –
@CodeInChaos,所有的事情都是平等的 - 即如果你可以在没有反思的情况下同样好地解决问题 - 不使用的解决方案反射更好,因为它更安全。 –