使用"窗口"未正确绘制WPF按钮样式.形状.路径



我目前正在学习MVVM模式的WPF,当我使用Windows绘制按钮时,我有一种"奇怪"的行为。形状。路径

通过一些测试,我将问题缩小到了纯WPF。这是我的XAML:

<Window x:Class="ButtonStyleTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:ButtonStyleTest"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<Style x:Key="MyButtonStyle" TargetType="Button">
<Setter Property="Background" Value="Red"/>
<Setter Property="Content">
<Setter.Value>
<Path Data="M1,9 L9,1 M1,1 L9,9" Stroke="White" StrokeThickness="2" />
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<WrapPanel Grid.Column="0"  >
<Button Style="{StaticResource MyButtonStyle}"/>
<Button Style="{StaticResource MyButtonStyle}"/>
</WrapPanel>
<WrapPanel Grid.Column="1"  >
<Button Style="{StaticResource MyButtonStyle}"/>
<Button Style="{StaticResource MyButtonStyle}"/>
</WrapPanel>
</Grid>

不幸的是,我不允许发布图片,因为我需要10个声誉:(所以我只是发布链接-很抱歉给您带来不便。

正在运行的程序如下所示
http://imageshack.com/a/img923/8541/HBAHyi.png

调整窗口大小后,按钮将以不同方式绘制
http://imageshack.com/a/img922/4600/gzEXWj.png

如果我使用字符串"X"作为内容,即

<Window.Resources>
<Style x:Key="MyButtonStyle" TargetType="Button">
<Setter Property="Background" Value="Red"/>
<Setter Property="Content" Value="x"/>
</Style>
</Window.Resources>

每个按钮都有"x"。

在我的实际应用程序中,我找到了一个变通方法。按钮绑定到ObservableCollection。如果我在数据模板中指定<Path Data... />标记,则所有内容都会正确显示。将其定义为按钮样式时,如上图所示。

然而,我想了解为什么路径属性在一种风格中不适合我。

更改您的风格,使其看起来像:

<Style x:Key="MyButtonStyle" x:Shared="False" TargetType="Button">
<Setter Property="Background" Value="Red"/>
<Setter Property="Content">
<Setter.Value>
<Path Data="M1,9 L9,1 M1,1 L9,9" Stroke="White" StrokeThickness="2" />
</Setter.Value>
</Setter>
</Style>

然后它会按照你想要的方式工作。

以下是关于x:Shared Attribute 的一些详细信息

基本上,它所做的是在设置为FALSE时创建样式的新实例。您需要为每个按钮创建一个新的PATH实例。

最新更新