2013-04-25 66 views
2

我正试图找到一种通用的方法来设置UIElement上的背景属性。获取UIElement或发件人的背景

我没有多少运气...

这里是我迄今(尝试使用反射来获取BackgroundProperty)。

Action<UIElement> setTheBrushMethod = (UIElement x) => 
    { 
    var brush = new SolidColorBrush(Colors.Yellow); 
    var whatever = x.GetType().GetField("BackgroundProperty"); 
    var val = whatever.GetValue(null); 
    ((UIElement)x).SetValue(val as DependencyProperty, brush); 
    brush.BeginAnimation(SolidColorBrush.ColorProperty, new ColorAnimation(Colors.White, TimeSpan.FromSeconds(3))); 
    }; 
    setTheBrushMethod(sender as UIElement); 

的事情是......它适用于像TextBlock的,但对于像一个StackPanel或按钮不起作用。

“无论”结束为StackPanel或Button为空。

我也觉得应该有一个简单的方法来一般地设置背景。我错过了明显吗?

背景似乎只能在System.Windows.Controls.Control上使用,但我无法转换为此。

+0

嗯....你有没有考虑使用样式? – failedprogramming 2013-04-26 00:36:31

回答

4

你的反射调用其实是错误的:你正在寻找的BackgroundPROPERTY,而不是BackgroundProperty的DependencyProperty

这里是应该是你的var whatever

var whatever = x.GetType().GetProperty("Background").GetValue(x); 
x.GetType().GetProperty("Background").SetValue(x, brush); 

而这将工作细

边注意事项:

我强烈建议你摆脱无用var,写你在等待的实际类型(在这种情况下,Brush),这将使你的代码更易于阅读

另外,为什么能你不是在Control上工作,而是在UIElement上工作?似乎对我来说很难得

干杯!

+0

干杯!这工作。 回复备注: 1. var是我从ReSharper领取的坏习惯。同意。 2.我需要UIElement,因为这实际上是attachedProperty中元数据更改事件的一部分。我有一个RoutedEvent attachedProperty,它会触发给定UIElement的脉冲。 难以解释通过互联网。 您的帮助非常感谢。 – tronious 2013-04-26 04:25:36