我有从 Control 类派生的自定义控件。我想创建另一个控件(例如按钮)的依赖属性并将其放置在 ControlTemplate 中(因此按钮可以放置在 xaml 中并且 MyControl 的用户可以订阅它的事件等)。有人可以告诉我,我该怎么做?
这是结果代码示例:
public class MyControl: Control
{
static MyControl( )
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(MyControl), new FrameworkPropertyMetadata(typeof(MyControl)));
}
public static readonly DependencyProperty MyButtonProperty =
DependencyProperty.Register("MyButton",
typeof(Button),
typeof(MyControl),
new PropertyMetadata(default(Button)));
public Button MyButton
{
get
{
return (Button) GetValue(MyButtonProperty);
}
set
{
SetValue(MyButtonProperty, value);
}
}
}
xml:
<ControlTemplate TargetType="{x:Type lib:MyControl}">
<Canvas>
<Border Child="{TemplateBinding MyButton}">
</Border>
</Canvas>
</ControlTemplate>