【发布时间】:2013-04-25 21:19:17
【问题描述】:
我正在尝试找到一种通用方法来设置 UIElement 上的 Background 属性。
我运气不太好……
这是我目前所拥有的(尝试使用反射来获取 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 或 Button 之类的东西。
对于 StackPanel 或 Button,“whatever”最终为 null。
我也觉得应该有一种简单的方法来通用地设置背景。我是不是很明显?
Background 似乎仅在 System.Windows.Controls.Control 上可用,但我无法强制转换。
【问题讨论】:
-
hmm.... 你考虑过使用 Styles 吗?
标签: c# wpf background dependency-properties uielement