我为您准备了一个示例,涉及到自定义控件
(与用户控件
相对)
步骤1:
创建一个新类(只有代码,没有XAML),继承自ContentControl
(或其他具有类似所需功能的UI元素)
public class ReusableContainer : ContentControl
{
public static readonly DependencyProperty ButtonProperty = DependencyProperty.Register("Button", typeof(Button), typeof(ReusableContainer), new PropertyMetadata(default(Button)));
public Button Button
{
get { return (Button)GetValue(ButtonProperty); }
set { SetValue(ButtonProperty, value); }
}
}
看看我在这里如何将
Button
属性定义为DependencyProperty。您可以为自定义控件中需要的任何“内容占位符”添加更多DP。
第二步:
在单独的
ResourceDictionary
中拥有UI元素内部容器的预定义样式:
CustomStyles.xaml
。
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Style TargetType="Button">
<Setter Property="Background" Value="Green"/>
</Style>
</ResourceDictionary>
步骤三:在 app.xaml
文件中,为 ReusableContainer
定义一个应用程序级别的样式,该样式定义了它的模板:
<Application x:Class="WpfApplication14.App"
xmlns="http:
xmlns:x="http:
xmlns:local="clr-namespace:WpfApplication14"
StartupUri="MainWindow.xaml">
<Application.Resources>
<Style TargetType="">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="">
<ControlTemplate.Resources>
<ResourceDictionary Source="CustomStyles.xaml"/>
</ControlTemplate.Resources>
<ContentPresenter Content=""/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Application.Resources>
</Application>
请注意我如何使用TemplateBinding
表达式来定义ContentPresenter
的内容将由ReusableContainer
中的Button
属性定义。
同时,请注意我如何将CustomStyles.xaml
中的资源添加到ControlTemplate.Resources
集合中。这使得这些资源对模板内的所有UI元素都可用。
步骤4:
在窗口中放置您的ReusableContainer
:
<Window x:Class="WpfApplication14.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication14"
Title="MainWindow" Height="350" Width="525">
<StackPanel>
<local:ReusableContainer>
<local:ReusableContainer.Button>
<Button x:Name="Button1" Content="Hello! Button 1"/>
</local:ReusableContainer.Button>
</local:ReusableContainer>
<local:ReusableContainer>
<local:ReusableContainer.Button>
<Button x:Name="Button2" Content="Hello! Button 2"/>
</local:ReusableContainer.Button>
</local:ReusableContainer>
<local:ReusableContainer>
<local:ReusableContainer.Button>
<Button x:Name="Button3" Content="Hello! Button 3"/>
</local:ReusableContainer.Button>
</local:ReusableContainer>
</StackPanel>
</Window>
Name
属性时,可以使用x:Name
属性,但就像@HighCore所说,为什么要这样做呢? 回答您的问题,创建CustomControl
的“正确”方法可以在MSDN上的控件编写概述页面中找到。 - Sheridan