gpt4 book ai didi

wpf - 如何在 WPF 按钮中绘制与控件大小相同的形状或线条,而不会导致按钮永远展开?

转载 作者:行者123 更新时间:2023-12-04 10:02:12 26 4
gpt4 key购买 nike

我快速搜索了一下 Google,并快速浏览了 StackOverflow,但找不到其他遇到此问题的人。

我想创建一个带有小 X 的关闭按钮。当您将鼠标悬停在包含它的项目上时,关闭按钮将执行淡入和淡出,当您将鼠标悬停时更改颜色,以及所有常见的 WPF 可爱。最重要的是,这似乎不应该那么困难,但在我到达这个阶段之前,我遇到了最奇怪的问题之一。

这是我的按钮的 XAML 样式:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Style x:Key="TabCloseButtonStyle" TargetType="{x:Type Button}">
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="Content">
<Setter.Value>
<Grid>
<Line Stroke="{Binding RelativeSource={RelativeSource AncestorType=Button}, Path=Foreground}"
X1="0"
Y1="0"
X2="{Binding RelativeSource={RelativeSource AncestorType=Grid}, Path=ActualWidth, Mode=OneWay}"
Y2="{Binding RelativeSource={RelativeSource AncestorType=Grid}, Path=ActualHeight, Mode=OneWay}"/>
<Line Stroke="{Binding RelativeSource={RelativeSource AncestorType=Button}, Path=Foreground}"
X1="0"
Y1="{Binding RelativeSource={RelativeSource AncestorType=Grid}, Path=ActualHeight, Mode=OneWay}"
X2="{Binding RelativeSource={RelativeSource AncestorType=Grid}, Path=ActualWidth, Mode=OneWay}"
Y2="0"/>
</Grid>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>

我创建了我的按钮,就像一个测试,像这样:
<Window x:Class="WpfTestApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="124" Width="569">
<Grid Background="#2b3c59">
<StackPanel Orientation="Horizontal">

<!-- Other controls removed for clarity -->

<Button Style="{DynamicResource TabCloseButtonStyle}"
HorizontalAlignment="Center"
VerticalAlignment="Bottom"
Padding="2"
Margin="0, 10, 0, 0"
MinWidth="50"
MinHeight="50"></Button>
</StackPanel>
</Grid>
</Window>

这就是一切都大错特错的地方。当您运行应用程序时,按钮将无限扩展,一次一个像素,水平和垂直扩展,直到达到窗口的高度。

现在我可以理解为什么会发生这种情况了:Lines 实际上超出了 Grid 的宽度和高度一个单位,导致 Grid 扩展了一个单位,然后进行了重新布局,数据绑定(bind)导致线条无限地重绘。

因此,为了尝试解决这个问题,我决定在网格中放置一个,但是无论我对 Horizo​​ntalAlignment 和 VerticalAlignment 做什么,我最终都会得到 Canvas 和 Grid 的宽度和高度都为零,这意味着我没有没有得到我的十字架,这非常令人恼火。如果我绑定(bind)到按钮的 ActualWidth 和 ActualHeight 属性,我最终会得到一个左上角以按钮中心为中心的 X。

有人知道我能做些什么来解决这个问题吗?我将非常感谢任何指点 - WPF 对我来说仍然是一个相当新的野兽。

谢谢!

最佳答案

你不应该仅仅为了布局而求助于绑定(bind)。如您所见,绑定(bind)和布局系统不能协同工作(我认为数据绑定(bind)优先于布局,但在您的情况下,布局会导致另一个数据绑定(bind))

你应该可以得到一个非常漂亮的、可拉伸(stretch)的 X,只需要一个路径:

<Path Data="M0,0 L1,1 M0,1 L1,0" Stretch="Uniform" Stroke="Red" />

如果您希望它使用按钮大小而不是拉伸(stretch)来缩放(缩放影响明显的笔划宽度),那么只需使用 ViewBox

关于wpf - 如何在 WPF 按钮中绘制与控件大小相同的形状或线条,而不会导致按钮永远展开?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4109625/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com