1

如果我有 2 Buttons, Aand B,是否可以创建 aStyle和 aTrigger这样当用户将鼠标悬停在 时Button B,它会导致Button A'sStyle改变?我尝试使用SourceNameand TargetName,但出现编译器错误。这是我正在玩弄的 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>

4

1 回答 1

0

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;
}
于 2009-08-10T19:09:25.827 回答