【发布时间】:2015-04-23 08:19:10
【问题描述】:
我有一个用户控件,我想在窗口的某些部分显示不同的控件模板。但我想将这些模板放在 UserControl 本身内(以便更好地维护)。这里是:
<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>
我在 Visual Studio 中收到错误消息,提示找不到资源并且控件未显示。如果我将模板更改为 DynamicResource,我会收到与警告相同的消息,但控件会显示。无论如何,程序运行良好。那么如何将 UserControl 和它的模板放在一起而不会收到这些烦人的警告/错误呢?我需要一个特定的 ResourceDictionary(另一个文件)吗?
【问题讨论】:
标签: c# wpf xaml user-controls controltemplate