C# 在WPF中,是否可以在UserControl本身内部为UserControl定义ControlTemplate(而不会在VS中获得警告/错误)?
我有一个UserControl,我想在窗口的某些部分显示不同的控件模板。但是我想把这些模板放在UserControl本身内部(为了更好地维护)。这是:C# 在WPF中,是否可以在UserControl本身内部为UserControl定义ControlTemplate(而不会在VS中获得警告/错误)?,c#,wpf,xaml,user-controls,controltemplate,C#,Wpf,Xaml,User Controls,Controltemplate,我有一个UserControl,我想在窗口的某些部分显示不同的控件模板。但是我想把这些模板放在UserControl本身内部(为了更好地维护)。这是: <UserControl x:Class="PruebasDeWPF.MyUserControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com
<UserControl x:Class="PruebasDeWPF.MyUserControl"
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:PruebasDeWPF"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<UserControl.Resources>
<ControlTemplate x:Key="UserControlTemplate1" TargetType="local:MyUserControl">
<Grid>
<Rectangle Fill="Red"></Rectangle>
</Grid>
</ControlTemplate>
<ControlTemplate x:Key="UserControlTemplate2" TargetType="local:MyUserControl">
<Grid>
<Rectangle Fill="Blue"></Rectangle>
</Grid>
</ControlTemplate>
</UserControl.Resources>
<Grid>
</Grid>
现在当我使用它时:
<Window x:Class="PruebasDeWPF.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:PruebasDeWPF"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<local:MyUserControl Template="{StaticResource UserControlTemplate1}"></local:MyUserControl>
</Grid>
</Window>
我在VisualStudio中收到一个错误,说找不到资源,控件未显示。如果将模板更改为DynamicSource,则会收到与警告相同的消息,但控件会显示。无论如何,程序运行良好。那么,如何在不出现这些恼人的警告/错误的情况下将UserControl及其模板保持在一起呢?我需要一个特定的ResourceDictionary(另一个文件)吗?您尝试执行的操作不适用于UserControl 尝试查找用于创建CustomControls的文章 基本上,您创建了一个新类(只是一个类),继承自ContentControl,并在提供的代码示例中使用名为“ContentTemplate”的属性,就像使用“Template”属性一样
如果要在控件中应用任何特定逻辑,请重写OnApplyTemplate方法如果将模板存储在控件中,则我认为您不能将其用作静态资源。见: 试图为无法解析的键指定StaticResource 在运行时引发XAML分析异常 您的控件在加载期间不存在,因此模板不存在,因此对模板不存在的键的引用失败
DynamicResources仅在运行时解析,这就是为什么程序运行时带有警告。设计器中的警告是“我现在找不到这个,但在程序运行时可能可以找到” 您尝试使用的模式并不适合资源,因为它们的加载方式是自顶向下的树。要在内部定义的选项之间进行切换,最好在
UserControl
(dependencProperty
如果要绑定它)上定义一个属性,该属性可以指示应该使用哪些可用模板。这可以是一个字符串、一个数字,或者(可能是最好的选项)一个列出可用选项的enum
。在UserControl
中,您可以根据该值切换使用的内部定义模板。此基本方法用于各种框架控件-例如Slider.Orientation
Ok,因此我添加了一个依赖属性(code behind中的枚举)和一个样式(xaml)以基于该属性值更改模板。谢谢