【问题标题】:Howto: Applying a Style defined in generic.xaml to a UserControl? (WPF)Howto:将 generic.xaml 中定义的样式应用于 UserControl? (WPF)
【发布时间】:2011-05-05 13:00:00
【问题描述】:

我在 generic.xaml 中创建了一个样式,我想在我的项目中的几个 UserControls 上使用它。以同样的方式,我为自定义控件定义了一种样式,并且这个样式有效,因此看起来 generic.xaml 已加载,这是定义的样式:

<Style TargetType="{x:Type UserControl}" x:Key="ServiceStyle" x:Name="ServiceStyle">
    <Setter Property="Opacity" Value="0.5"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type UserControl}">
                <Border Name="border" CornerRadius="20"
                        Margin="10"
                        BorderThickness="5"
                        BorderBrush="Black">
                        <ContentPresenter Content="{TemplateBinding Content}"
                                          Margin="{TemplateBinding Padding}"/>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

但现在我想使用这种风格,但我无法让它发挥作用。我尝试通过以下方式将其作为样式参数添加到 UserControl 的自定义实例中:

<UserControl
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:Netcarity"
    xmlns:CustomControls="clr-namespace:Netcarity.CustomControls"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" x:Name="Portier_deur" x:Class="Netcarity.UserControlPortier"
    Height="600" Width="800" MouseDown="UserControl_MouseDown" Loaded="UserControl_Loaded" mc:Ignorable="d"
    Style="{StaticResource ServiceStyle}">

但是,这让我注意到找不到资源 ServiceStyle。尝试运行时出现运行时错误。

提前致谢。

【问题讨论】:

  • 重新标记,假设您想要 'WPF' 而不是 'WFP'

标签: wpf xaml styles generic.xaml


【解决方案1】:

Generic.xaml 似乎不是为非自定义控件存储样式的正确位置。在某处我发现将样式放入 App.xaml 而不是 generic.xaml 的提示,这直接起作用。所以它接缝Generic.xaml 只能用于存储customControls 的样式。 也许有人可以为这种行为添加一个更有根据的理由?

【讨论】:

    【解决方案2】:

    当 Generic.xaml 使用 ComponentResourceKey。

    【讨论】:

      猜你喜欢
      • 2010-12-02
      • 2019-10-17
      • 2010-12-13
      • 2012-06-24
      • 2019-03-11
      • 2011-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多