【问题标题】:WPF Style Trigger on Foreign UIElement外部 UIElement 上的 WPF 样式触发器
【发布时间】:2009-08-10 18:29:30
【问题描述】:

如果我有 2 个Buttons、AB,是否可以创建一个Style 和一个Trigger,这样当用户将鼠标悬停在Button B 上时,会导致@987654327 @的Style要改变吗?我试过使用SourceNameTargetName,但遇到编译器错误。这是我正在玩弄的 XAML - 我想让Button A 的内容在Button B 被鼠标悬停时加粗:

<Window x:Class="WpfApplication1.Window4"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window4" Height="300" Width="300">

<Window.Resources>
    <Style x:Key="BoldWhenOver" TargetType="{x:Type Button}">
        <Style.Triggers>
            <Trigger Property="IsMouseOver" Value="True">
                <Setter Property="FontWeight" Value="Bold" />
            </Trigger>
        </Style.Triggers>
    </Style>
</Window.Resources>

<StackPanel>
    <Button Name="btnA" Content="A" Style="{StaticResource BoldWhenOver}" />
    <Button Name="btnB" Content="B" />
</StackPanel>

【问题讨论】:

    标签: wpf xaml triggers uielement


    【解决方案1】:

    Triggers,就其性质而言,用于更改触发器应用于的元素的属性,而不是其他不相关的元素。您可能可以实施一些技巧来使这样的事情发生,但我认为这不是一个好的做法,也不符合 WPF 的意图。

    您可以将 btnAbtnB 嵌入到单个用户控件中(然后可以在 UserControl.Triggers 中访问两者),但这可能没有逻辑意义对于你想要做的事情。这就假设 btnA 和 btnB 总是属于一起的。如果不是这种情况,你应该用老式的方式把它连接起来,有几个事件和一些代码隐藏:

    <StackPanel>
       <Button Name="btnA" Content="A"/>
       <Button Name="btnB" Content="B" MouseEnter="btnB_MouseEnter" MouseLeave="btnB_MouseLeave"/>
    </StackPanel>
    

    还有代码:

    private void btnB_MouseEnter(object sender, MouseEventArgs e)
    {
        btnA.FontWeight = FontWeights.Bold;
    }
    
    private void btnB_MouseLeave(object sender, MouseEventArgs e)
    {
        btnA.FontWeight = FontWeights.Normal;
    }
    

    【讨论】:

    • 感谢您的回答。我希望用一些直接的 XAML 来做到这一点,但我接受了你的第二个建议,它运作良好。
    猜你喜欢
    • 2012-04-23
    • 2010-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多