【问题标题】:WPF Buttonstyle not properly drawn using Window.Shapes.Path使用 Window.Shapes.Path 未正确绘制 WPF Buttonstyle
【发布时间】:2016-05-19 17:41:55
【问题描述】:

我目前正在学习带有 MVVM 模式的 WPF,当我使用 Windows.Shapes.Path 绘制按钮时,我的行为很“奇怪”。

进行一些测试后,我将问题缩小到纯 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。如果我在 Datatemplate 中指定 &lt;Path Data... /&gt; 标签,一切都会正确显示。将其定义为按钮样式时,如上所示。

但是,我想了解为什么 path 属性在样式中不适合我。

【问题讨论】:

    标签: c# wpf xaml button wpf-style


    【解决方案1】:

    改变你的风格,让它看起来像:

    <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 的新实例。

    【讨论】:

      猜你喜欢
      • 2022-01-17
      • 2013-02-25
      • 2016-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多