在资源字典中使用WPF参考样式和触发器

3

我在资源字典中定义了一个Style,该样式适用于所有的ComboBox控件。在ComboBox控件内部,我可以通过以下方式引用该样式:

Style="{DynamicResource MyComboBoxStyle}"

这个做法还算不错。

我想要在某些ComboBox控件上添加一些Trigger

如何使用作为动态资源引用的Style,同时仍然能够向某些ComboBox控件添加Trigger

2个回答

1

更新: 重新阅读问题后,我意识到这并不完全是OP所询问的内容。我可以删除它,但或许对那些偶然发现这个问题的人有用。


这里是一个例子,使用XAML资源字典定义了模板和触发器,以及引用该资源并应用样式的窗口。以下是需要翻译的内容:

这可能会帮助那些想使用模板和触发器的人:

我的资源名为“Style1.xaml”

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<ControlTemplate x:Key="TonyTemplate" TargetType="Button">
    <Border Name="Border" 
            BorderBrush="Orange" 
            BorderThickness="3" 
            CornerRadius="2" 
            Background="Ivory" 
            TextBlock.Foreground="Black">
        <Grid>
            <ContentPresenter RecognizesAccessKey="True" 
                              Margin="{TemplateBinding Padding}"/>
        </Grid>
    </Border>
    <ControlTemplate.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
            <Setter TargetName="Border" Property="Background" Value="Yellow" />
        </Trigger>
        <Trigger Property="IsPressed" Value="True">
            <Setter TargetName="Border" Property="Background" Value="Chartreuse" />
            <Setter TargetName="Border" Property="BorderBrush" Value="DarkKhaki" />
        </Trigger>
    </ControlTemplate.Triggers>
</ControlTemplate>

我的MainWindow代码xaml:
<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Style1.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Window.Resources>
    <Grid>
        <Button Width="100" Height="50" 
                Template="{StaticResource TonyTemplate}" 
                Content="Click me"/>
    </Grid>
</Window>

0

为您想要应用触发器的ComboBox控件创建新样式,并在新样式上使用BasedOn属性来设置它们的基础样式。


当我尝试这样做时,我会收到以下错误提示: 无法在“Style”类型的“BasedOn”属性上设置“DynamicResourceExtension”。 - Rob Buhler
你为什么要使用DynamicResource呢?对于设置样式,StaticResource应该可以胜任。 - Charlie
样式位于单独的模块中(使用CAL),因此我必须指定DynamicResource才能使用它。 - Rob Buhler
所以基本上这个问题还没有解决... 我也想要一个答案。 - Paul-Sebastian Manole

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接