[英]Property Gets The Default Value After Calling PropertyInfo.SetValue
I am using reflection to set a value of a property, but it is not working! 我正在使用反射来设置属性的值,但是它不起作用! this is because the default color is resetting after! 这是因为默认颜色将在之后重设! That's is my code: 那是我的代码:
MapWindow.xaml: MapWindow.xaml:
<Window x:Class="MapRepresentation.MapWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MapWindow" SizeToContent="WidthAndHeight">
<Grid Width="640" Height="739">
<Path x:Name="akkar" Data="..." HorizontalAlignment="Right" Height="124.318" Margin="0,6.482,82.619,0" Stretch="Fill" Stroke="Red" VerticalAlignment="Top" Width="211.881" />
</Grid>
</Window>
MapWindow.Xaml.cs: MapWindow.Xaml.cs:
public Brush AkkarColor
{
get { return this.akkar.Fill; }
set { this.akkar.Fill = value; }
}
public void ChangeColor()
{
Type type = GetType();
object obj = Activator.CreateInstance(type);
PropertyInfo pathInfo = type.GetProperty("AkkarColor");
pathInfo.SetValue(obj, System.Windows.Media.Brushes.Red, null);
}
private void akkar_MouseEnter(object sender, MouseEventArgs e)
{
ChangeColor();
}
what is wrong ? 怎么了 ? why the color of the path Akkar is not changing? 为什么路径Akkar的颜色没有改变?
It is because you are creating a new instance of the MapWindow
. 这是因为您正在创建MapWindow
的新实例。 Pass this
to SetValue
. this
传递给SetValue
。
public void ChangeColor()
{
Type type = GetType();
PropertyInfo pathInfo = type.GetProperty("AkkarColor");
pathInfo.SetValue(this, System.Windows.Media.Brushes.Red, null);
}
You're creating a new instance of the current type, setting a property on it, and then ignoring the newly created object. 您正在创建当前类型的新实例,在其上设置属性,然后忽略新创建的对象。 I suspect you want to change the property on the current object, ie 我怀疑您想更改当前对象的属性,即
// Remove the line declaring and initializing obj
pathInfo.SetValue(this, System.Windows.Media.Brushes.Red, null);
Having said that, it's not at all clear why you're using reflection in the first place. 话虽如此,目前尚不清楚为什么首先要使用反射。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.