Wpf 如何使用控件模板扩展用户控件?
我是WPF新手,我想了解如何扩展UserControlBase类,在其他用户控件子类中添加一些控件。 详细地说,我有一个UserControlBase示例,在控件模板中定义了两个按钮:Wpf 如何使用控件模板扩展用户控件?,wpf,Wpf,我是WPF新手,我想了解如何扩展UserControlBase类,在其他用户控件子类中添加一些控件。 详细地说,我有一个UserControlBase示例,在控件模板中定义了两个按钮: <UserControl x:Class="Test.UserControlBase" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.co
<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>
按钮1
按钮3
现在我想扩展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>
按钮2
此代码无法工作,因为无法解析“Decorator”。我不知道如何从UserControlBase链接。我知道,如果我将控件模板放入App.xaml中,这会起作用,但我的目的是扩展UserControlBase。您可以在基类中添加一个属性,以便为您获取模板,如下所示:
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>
按钮2
另一种解决方案是将ControlTemplate放在ResourceDictionary中,而不是放在UserControlBase资源中,并将此字典加载到UserControlChild控件中。然后您可以从子控件使用它
希望有帮助 谢谢你的回答。我尝试了第一个方法,收到错误“Test.UserControlBase”不能是XAML文件的根,因为它是使用XAML定义的。我了解到继承XAML是不可能的。因为您的UserControlBase没有XAML,而是一个控件模板,所以您可以将其设置为CustomControl而不是UserControl。您必须在资源字典(如第二种方法)中声明模板。我将尝试使用ResourceDictionary,正如您在第二种方法中所说的那样。谢谢