2011-08-28 21 views
0

我正在使用反射設置屬性的值,但它不起作用!這是因爲默認顏色在重設後!這是我的代碼:Property在調用PropertyInfo.SetValue後獲取默認值

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的顏色沒有改變?

+0

你爲什麼要通過反射來做這件事?有一種更簡單的方法... –

回答

2

這是因爲您正在創建MapWindow的新實例。通過thisSetValue

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

您正在創建當前類型的新實例,在其上設置屬性,然後忽略新創建的對象。我懷疑你想改變當前對象的屬性,即

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

話雖如此,但爲什麼你在第一時間使用反射並不完全清楚。