【发布时间】:2013-01-14 12:48:30
【问题描述】:
在 WPF 项目中,我有一堆控件,我希望能够在其中设置单独的 Margin 属性并保留其他值。所以,我想避免将完整边距设置为新的Thickness (Margin="0,5,0,15")。因为许多边距是从样式等设置的。但在个别情况下,我想偏离某些控件的通用样式。
我想,为什么不像这样在 .NET 类FrameWorkElement 上注册几个新的依赖属性(例如只显示 MarginLeft):
public class FrameWorkElementExtensions: FrameworkElement
{
public static readonly DependencyProperty MarginLeftProperty = DependencyProperty.Register("MarginLeft", typeof(Int16?), typeof(FrameworkElement), new PropertyMetadata(null, OnMarginLeftPropertyChanged));
public Int16? MarginLeft
{
get { return (Int16?)GetValue(MarginLeftProperty); }
set { SetValue(MarginLeftProperty, value); }
}
private static void OnMarginLeftPropertyChanged(object obj, DependencyPropertyChangedEventArgs e)
{
if (obj != null && obj is UIElement)
{
FrameworkElement element = (FrameworkElement)obj;
element.Margin = new Thickness((Int16?)e.NewValue ?? 0, element.Margin.Top, element.Margin.Right, element.Margin.Bottom);
}
}
}
但此属性在代码隐藏或 XAML 中不可用。我能以某种方式理解它,因为这个虚拟类永远不会被实例化或任何东西。试图使它成为一个静态类,但你不能从 FrameWorkElement 派生(我需要 GetValue 和 SetValue 方法)。
我在网上找不到任何资源来处理更通用的问题:您可以将依赖项属性添加到现有的 .NET 类吗?
感谢任何帮助/明智的建议。
顺便说一句:仅更改边距(厚度)的一个组件的解决方案也值得赞赏;)
【问题讨论】:
-
您可能想查看attached properties。
-
为什么没有说明原因就被否决了?似乎是一个合理的问题。