我想創建一個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