【问题标题】:Getting the Background of a UIElement or sender获取 UIElement 或发送者的背景
【发布时间】: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


【解决方案1】:

您的反射调用实际上是错误的:您正在寻找Background PROPERTY,而不是BackgroundProperty DEPENDENCYPROPERTY

这应该是你的var whatever

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

这会很好用

旁注:

我强烈建议您摆脱无用的var,并编写您正在等待的实际类型(在本例中为Brush),这将使您的代码更易于阅读

另外,为什么你不能只处理 Control 而不是 UIElement ?对我来说似乎很少见

干杯!

【讨论】:

  • 干杯!这行得通。回复您的笔记: 1. var 是我从 ReSharper 学到的一个坏习惯。同意。 2. 我需要 UIElement,因为这实际上是附加属性中元数据更改事件的一部分。我有一个 RoutedEvent attachProperty,它将触发给定 UIElement 的脉冲。很难通过互联网解释。非常感谢您的帮助。
猜你喜欢
  • 2020-10-26
  • 1970-01-01
  • 2011-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-28
相关资源
最近更新 更多