[XAML] 使用 ContentPropertyAttribute 指定 Content,讓自訂控制項可以直接指定 Content
假設我已經建立了一個自訂控制項名為 DemoControl,並擁有 DemoContent 屬性 (如下)
public class DemoControl : Control
{
public static readonly DependencyProperty DemoContentProperty =
DependencyProperty.Register("DemoContent", typeof(DependencyObject), typeof(DemoControl), new PropertyMetadata(default(DependencyObject)));
public DependencyObject DemoContent
{
get { return (DependencyObject)GetValue(DemoContentProperty); }
set { SetValue(DemoContentProperty, value); }
}
}
若想將一個名為 DemoTextBlock 的 TextBlock 控制項指定給 DemoControl 的 DemoContent 屬性時,可以寫成下列 XAML
<DemoControl>
<DemoControl.DemoContent>
<TextBlock x:Name="DemoTextBlock" />
</DemoControl.DemoContent>
</DemoControl>
若覺得 XAML 階層太多,或者希望其他開發人員可以直接指定 DemoControl 的內容時 (如下),必須做一些額外處理
<DemoControl>
<TextBlock x:Name="DemoTextBlock" />
</DemoControl>
由於編譯器不知道指定的內容需要對應到哪一個屬性,所以必須設定 DemoControl 的 ContentPropertyAttribute
[System.Windows.Markup.ContentProperty(nameof(DemoContent))]
public class DemoControl : Control
{
...
}
完整範例
[System.Windows.Markup.ContentProperty(nameof(DemoContent))]
public class DemoControl : Control
{
public static readonly DependencyProperty DemoContentProperty =
DependencyProperty.Register("DemoContent", typeof(DependencyObject), typeof(DemoControl), new PropertyMetadata(default(DependencyObject)));
public DependencyObject DemoContent
{
get { return (DependencyObject)GetValue(DemoContentProperty); }
set { SetValue(DemoContentProperty, value); }
}
}
<DemoControl>
<TextBlock x:Name="DemoTextBlock" />
</DemoControl>