tro*_*ous 2 c# wpf background dependency-properties uielement
我正在尝试找到一种在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);
Run Code Online (Sandbox Code Playgroud)
事情是......它适用于类似TextBlock的东西,但不适用于像StackPanel或Button这样的东西.
对于StackPanel或Button,"whatever"最终为null.
我也觉得应该有一个简单的方法来一般设置背景.我错过了吗?
后台似乎只在System.Windows.Controls.Control上可用,但我无法转换为.
您的反映调用实际上是错误的:您正在寻找Background 属性,而不是BackgroundProperty DEPENDENCYPROPERTY
这应该是你的var whatever:
var whatever = x.GetType().GetProperty("Background").GetValue(x);
x.GetType().GetProperty("Background").SetValue(x, brush);
Run Code Online (Sandbox Code Playgroud)
这将很好
侧面说明:
我强烈建议你摆脱无用var并写下你正在等待的实际类型(在这种情况下,a Brush),这将使你的代码更容易阅读
另外,为什么你不能只在一个Control而不是一个UIElement?对我来说似乎很少见
干杯!