我想创建一个GUI(WPF)库,其中每个(自定义)控件基本上包装内部(第三方)控件。然后,我手动公开每个属性(不是全部,但几乎)。在XAML中所产生的控制是非常简单的:包装WPF控制
<my:CustomButton Content="ClickMe" />
而后面的代码非常简单,以及:
public class CustomButton : Control
{
private MyThirdPartyButton _button = null;
static CustomButton()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomButton), new FrameworkPropertyMetadata(typeof(CustomButton)));
}
public CustomButton()
{
_button = new MyThirdPartyButton();
this.AddVisualChild(_button);
}
protected override int VisualChildrenCount
{
get
{ return _button == null ? 0 : 1; }
}
protected override Visual GetVisualChild(int index)
{
if (_button == null)
{
throw new ArgumentOutOfRangeException();
}
return _button;
}
#region Property: Content
public Object Content
{
get { return GetValue(ContentProperty); }
set { SetValue(ContentProperty, value); }
}
public static readonly DependencyProperty ContentProperty = DependencyProperty.Register(
"Content", typeof(Object),
typeof(CustomButton),
new FrameworkPropertyMetadata(new PropertyChangedCallback(ChangeContent))
);
private static void ChangeContent(DependencyObject source, DependencyPropertyChangedEventArgs e)
{
(source as CustomButton).UpdateContent(e.NewValue);
}
private void UpdateContent(Object sel)
{
_button.Content = sel;
}
#endregion
}
问题就来了后,我们暴露了MyThirdPartyButton作为属性(如果我们不这样做揭露一些东西,我们想让程序员直接使用它)。通过简单地创建属性,像这样:
public MyThirdPartyButton InternalControl
{
get { return _button; }
set
{
if (_button != value)
{
this.RemoveVisualChild(_button);
_button = value;
this.AddVisualChild(_button);
}
}
}
产生的XAML会是这样:
<my:CustomButton>
<my:CustomButton.InternalControl>
<thirdparty:MyThirdPartyButton Content="ClickMe" />
</my:CustomButton.InternalControl>
什么我要找的,是这样的:
<my:CustomButton>
<my:CustomButton.InternalControl Content="ClickMe" />
但是(使用我的代码)不可能为InternalControl添加属性...
任何想法/建议吗?
非常感谢,
- 罗伯特
谢谢雷。第二个解决方法就像魅力一样。是的,这将是棘手的,以产生所有这些属性... 第一个解决方法不直接在setter中工作。这可能是因为那时对象尚未初始化。无论如何,如果您在初始化(value.Initialized + = HANDLER)之后通过GetLocalValueEnumerator()迭代它就可以工作。如果我错了,请纠正我。 我仍然必须检查“InternalControl”属性上的绑定是否正常工作。其实,我要检查: -Bindings -styles 靶向性风格 -ControlTemplates -ItemTemplates -Validations - ??? – Robert 2010-05-14 12:51:12