我希望在给定属性的情况下获得字符串表示。这样,我就可以将这个字符串用于NotifyPropertyChanged
,并且在重构属性名称之后仍然可以正常工作。
编辑:我使用的是.NET 4.0
更新:我还希望DependencyProprty
的名称可用,即我需要在静态变量赋值时使用该值。
相同的示例代码来解释:
// actual code
private int prop = 42;
public int Prop
{
get
{
return prop;
}
set
{
prop = value;
NotifyPropertyChanged("Prop"); // I'd like to replace the hard-coded string here
}
}
// code as I'd like it to be
private int propNew = 42;
private static readonly string PropNewName = GainStringFromPropertySomeHow(PropNew); // should be "PropNew"
public int PropNew
{
get
{
return propNew;
}
set
{
propNew = value;
NotifyPropertyChanged(PropNewName); // <== will remain correct even if PropNew name is changed
}
}
重构后:
private int prop = 42;
public int PropNameChanged
{
get
{
return prop;
}
set
{
prop = value;
NotifyPropertyChanged("Prop"); // oops
}
}
private int propNew = 42;
private static readonly string PropNewName = GainStringFromPropertySomeHow(PropNewNameChanged); // should be "PropNewNameChanged"
public int PropNewNameChanged
{
get
{
return propNew;
}
set
{
propNew = value;
NotifyPropertyChanged(PropNewName); // still correct
}
}
发布于 2013-08-01 08:54:59
我认为这可能是有帮助的:
// This method is called by the Set accessor of each property.
// The CallerMemberName attribute that is applied to the optional propertyName
// parameter causes the property name of the caller to be substituted as an argument.
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
来源和更多解释:http://msdn.microsoft.com/de-de/library/system.componentmodel.inotifypropertychanged.aspx
发布于 2013-08-01 09:05:00
如果您还没有使用.Net 4.5,因此不能使用CallerMemberName,您可以使用以下方法:https://stackoverflow.com/a/3191598/869250
发布于 2013-08-01 09:05:19
这是How to get current property name via reflection?的副本
所以你可以这样做
NotifyPropertyChanged(MethodBase.GetCurrentMethod().Name);
https://stackoverflow.com/questions/17989201
复制