Property在调用PropertyInfo.SetValue后获取默认值

时间:2011-08-28 14:59:27

标签: 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="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:

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();
}

有什么不对?为什么Akkar路径的颜色没有改变?

2 个答案:

答案 0 :(得分:2)

这是因为您正在创建MapWindow的新实例。将this传递给SetValue

public void ChangeColor()  
{  
   Type type = GetType();  
    PropertyInfo pathInfo = type.GetProperty("AkkarColor");  
    pathInfo.SetValue(this, System.Windows.Media.Brushes.Red, null);  
}  

答案 1 :(得分:2)

您正在创建当前类型的新实例,在其上设置属性,然后忽略新创建的对象。我怀疑你想要改变当前对象的属性,即

// Remove the line declaring and initializing obj
pathInfo.SetValue(this, System.Windows.Media.Brushes.Red, null); 

话虽如此,但一开始并不清楚你为什么要使用反射。