【发布时间】:2010-05-18 22:37:28
【问题描述】:
我正在尝试创建一个 GUI (WPF) 库,其中每个(自定义)控件基本上都包含一个内部(第三方)控件。然后,我手动公开每个属性(不是全部,但几乎)。在 XAML 中,生成的控件非常简单:
<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...
有什么想法/建议吗?
非常感谢,
-- 罗伯特
【问题讨论】:
标签: c# wpf custom-controls