使用自定义窗口镶边时如何向 WPF 标题栏添加按钮?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12431112/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I add a button to the WPF caption bar while using custom window chrome?
提问by Chris Covert
I'm attempting to create a simple button template in which the button normally looks like a single horizontal line, but when moused over, the button will display a "rectangle" color fill behind it. This is the code I have, but I can't seem to get the triggers to fire.
我正在尝试创建一个简单的按钮模板,其中按钮通常看起来像一条水平线,但是当鼠标悬停在按钮上时,按钮将在其后面显示一个“矩形”颜色填充。这是我拥有的代码,但我似乎无法触发触发器。
<Window x:Class="TestStylingWPF.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<WindowChrome.WindowChrome>
<WindowChrome CaptionHeight="36" GlassFrameThickness="0 0 0 1" ResizeBorderThickness="5" />
</WindowChrome.WindowChrome>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="36" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Button Height="36" Width="36"
HorizontalAlignment="Center" VerticalAlignment="Center"
Grid.Row="0">
<Button.Template>
<ControlTemplate>
<Grid>
<Rectangle x:Name="PART_ButtonBackgroundRectangle" Fill="LightGray" Width="36" Height="36" Opacity="0" />
<Path x:Name="PART_ButtonPath" Data="M10,26 L26,26" Stroke="DarkGray" StrokeThickness="1.5" />
</Grid>
<ControlTemplate.Triggers>
<Trigger SourceName="PART_ButtonBackgroundRectangle" Property="IsMouseOver" Value="True">
<Setter TargetName="PART_ButtonBackgroundRectangle" Property="Opacity" Value="1" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Button.Template>
</Button>
</Grid>
</Window>
Does anyone know why my trigger won't work, or perhaps a better way to do this? I'm sort of new to WPF and would like to refactor this out (so as to use it in many buttons), but am unsure how.
有谁知道为什么我的触发器不起作用,或者有更好的方法来做到这一点?我对 WPF 有点陌生,想重构它(以便在许多按钮中使用它),但我不确定如何。
Update:Ok, so I guess it appears to be because the button is within the caption bar of the window. Is there a good way around this? Maybe a way to set click/hover priority to the button?
更新:好的,所以我想这似乎是因为该按钮位于窗口的标题栏中。有什么好的方法可以解决这个问题吗?也许是一种为按钮设置点击/悬停优先级的方法?
回答by Erti-Chris Eelmaa
You need to set Hittest visible of your button, such as:
您需要设置按钮的 Hittest 可见,例如:
shell:WindowChrome.IsHitTestVisibleInChrome="True"

