C# 属性在调用PropertyInfo.SetValue后获取默认值
我正在使用反射设置属性的值,但它不起作用!这是因为默认颜色在之后重置!这是我的代码: MapWindow.xaml:C# 属性在调用PropertyInfo.SetValue后获取默认值,c#,.net,wpf,xaml,reflection,C#,.net,Wpf,Xaml,Reflection,我正在使用反射设置属性的值,但它不起作用!这是因为默认颜色在之后重置!这是我的代码: 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="Ma
<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>
怎么了?为什么路径Akkar的颜色没有改变?这是因为您正在创建
映射窗口的新实例。将此
传递到设置值
public void ChangeColor()
{
Type type = GetType();
PropertyInfo pathInfo = type.GetProperty("AkkarColor");
pathInfo.SetValue(this, System.Windows.Media.Brushes.Red, null);
}
这是因为您正在创建MapWindow
的新实例。将此
传递到设置值
public void ChangeColor()
{
Type type = GetType();
PropertyInfo pathInfo = type.GetProperty("AkkarColor");
pathInfo.SetValue(this, System.Windows.Media.Brushes.Red, null);
}
您正在创建当前类型的新实例,在其上设置属性,然后忽略新创建的对象。我怀疑您想更改当前对象的属性,即
// Remove the line declaring and initializing obj
pathInfo.SetValue(this, System.Windows.Media.Brushes.Red, null);
尽管如此,我们还是不清楚为什么要首先使用反射。您要创建当前类型的新实例,在其上设置属性,然后忽略新创建的对象。我怀疑您想更改当前对象的属性,即
// Remove the line declaring and initializing obj
pathInfo.SetValue(this, System.Windows.Media.Brushes.Red, null);
话虽如此,我们还是不清楚为什么要首先使用反射。为什么要通过反射来实现这一点?有一个更简单的方法…你为什么要通过反射来做这件事?有一个更简单的方法。。。