我是WPF的新手,我想了解如何扩展UserControlBase类,以便在其他用户控件子级中添加一些控件。 详细地,我有一个示例UserControlBase,它在控件模板中定义了两个按钮:
<UserControl x:Class="Test.UserControlBase"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:Test"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<UserControl.Resources>
<ControlTemplate x:Key="Decorator" TargetType="{x:Type ContentControl}">
<StackPanel Orientation="Vertical" >
<Button x:Name="Button1" Click="Button1Click">Button1</Button>
<ContentPresenter />
<Button x:Name="Button3" Click="Button3Click">Button3</Button>
</StackPanel>
</ControlTemplate>
</UserControl.Resources>
</UserControl>
现在,我想扩展UserControlBase在UserControlChild中添加按钮2:
<UserControl x:Class="Test.UserControlChild"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:src="clr-namespace:Test"
mc:Ignorable="d" >
<StackPanel Orientation="Vertical">
<ContentControl Template="{StaticResource Decorator}">
<Button x:Name="Button2" Click="Button2_Click">Button2</Button>
</ContentControl>
</StackPanel>
</UserControl>
此代码不起作用,因为无法解析“装饰器”。我不知道如何从UserControlBase进行链接。我知道,如果我将控件模板放在App.xaml中,则可以使用,但是我的目的是扩展UserControlBase。
答案 0 :(得分:0)
您可以在基类中添加一个属性,该属性将为您提供模板,如下所示:
public ControlTemplate Decorator
{
get { return FindResource("Decorator") as ControlTemplate; }
}
然后,您的子类应为UserControlBase类型,而不是UserControl类型,然后将模板绑定到该类。所以您的孩子班级看起来像这样:
<UserControlBase x:Class="Test.UserControlChild"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:src="clr-namespace:Test"
mc:Ignorable="d"
x:Name=UserControl>
<StackPanel Orientation="Vertical">
<ContentControl Template="{Binding Decorator, ElementName=UserControl}">
<Button x:Name="Button2" Click="Button2_Click">Button2</Button>
</ContentControl>
</StackPanel>
</UserControlBase>
另一个解决方案是将ControlTemplate放在ResourceDictionary中,而不是放在UserControlBase资源中,然后将此字典加载到UserControlChild控件中。这样您就可以从子控件中使用它了。
希望有帮助!