外部 UIElement 上的 WPF 样式触发器
如果我有 2 个 Button
,A
和 B
,是否可以创建一个 Style
和一个 >触发器
,以便当用户将鼠标悬停在按钮B
上时,会导致按钮A
的样式
发生变化? 我尝试使用 SourceName
和 TargetName
,但出现编译器错误。 这是我正在使用的 XAML - 我希望当鼠标悬停在 Button B
上时,使 Button A
的内容变为粗体:
<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>
If I have 2 Button
s, A
and B
, is it possible to create a Style
and a Trigger
such that when the user hovers over Button B
, it will cause Button A
's Style
to change? I've tried using SourceName
and TargetName
, and am getting compiler errors. Here's the XAML that I'm fooling around with - I'd like to cause Button A
's content to be bolded when Button B
is moused over:
<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>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
触发器
本质上用于更改触发器所应用的元素的属性,而不是其他不相关元素的属性。 您可能可以实施一些技巧来实现这样的事情,但我认为这不是一个好的实践,也不适合 WPF 的用途。您可以将 btnA 和 btnB 嵌入到单个用户控件中(然后可以在 UserControl.Triggers 中访问这两个控件),但这对于您的内容来说可能没有逻辑意义正在努力做。 这使得 btnA 和 btnB 始终属于一起的假设。 如果情况并非如此,您应该以老式的方式连接它,使用几个事件和一些隐藏代码:
以及代码:
Trigger
s, by their nature, are used to change properties on the element the trigger is applied to, not other unrelated elements. There are probably some hacks you could implement to make something like this happen, but I don't think it would be good practice or fit with what WPF is meant to do.You could embed btnA and btnB into a single user-control (and then have access to both in the UserControl.Triggers), but that might not make logical sense for what you are trying to do. That makes the assumption that btnA and btnB always belong together. If that is not the case, you should just wire this up the old-fashioned way, with a couple events and some code-behind:
And the code: