c# - 在 WPF 中,是否可以在 UserControl 本身内部为 UserControl 定义 ControlTemplate(在 VS 中不会收到警告/错误)?

标签 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/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 (另一个文件)吗?

最佳答案

由于资源的加载方式,您尝试使用的模式并不真正适合资源:作为自上而下的树。要在内部定义的选项之间进行切换,更合适的做法是在 UserControl 上定义一个属性(DependencyProperty 如果您想绑定(bind)它),该属性可以指示哪些可用模板应该使用。这可以是字符串、数字或(可能是最好的选项)列出可用选项的enum。然后,您可以在 UserControl 内根据该值切换使用的内部定义模板。此基本方法用于各种框架控件 - 例如 Slider.Orientation

关于c# - 在 WPF 中,是否可以在 UserControl 本身内部为 UserControl 定义 ControlTemplate(在 VS 中不会收到警告/错误)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29817598/

相关文章:

c# - Windows Phone 8 按钮点击颜色

xaml - SL5 是 Win8 和 WP8 开发商店被迫开发 Win7 应用程序的最佳选择?

c# - 调用 Facebook/Google+ 时 ExternalLogin 未命中

c# - 如何获取 IMemoryCache 中 key 的 AbsoluteExpiration DateTimeOffset

wpf - 使复选框绑定(bind)到可空的 bool 转换从空到真

wpf - Prism RegionAdapter - 删除然后添加 View

wpf - 来自静态资源的WPF窗口标题

c# - 具有透明状态栏的 Xamarin Forms 背景图像

c# - FileSystemWatcher 超越文件系统权限

c# - 向 TreeView 添加图形