gpt4 book ai didi

wpf - 如何正确地将样式应用到内容展示器

转载 作者:行者123 更新时间:2023-12-04 20:15:03 24 4
gpt4 key购买 nike

我正在使用这个关于链接按钮的问题的答案:

https://stackoverflow.com/a/3564706/945

问题是 TextDecoration Underline 样式仅应用于自动生成的 TextBlock。

<Button Style="{StaticResource LinkButton}">Text</Button> 

“文本”有下划线
<Button Style="{StaticResource LinkButton}"><TextBlock Text='Text' /></Button> 

“文本”没有下划线

为什么它不适用于内容中的任何 TextBlock?

这是样式的相关部分:
<Style x:Key="LinkButton" 
TargetType="Button"
BasedOn="{StaticResource ResourceKey={x:Type Button}}"
>

<Setter Property="Width" Value="Auto"/>

<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<ContentPresenter Content="{TemplateBinding Content}"
ContentTemplate="{TemplateBinding ContentTemplate}"
VerticalAlignment="Center"
>
<ContentPresenter.Resources>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="TextDecorations" Value="Underline" />
</Style>
</ContentPresenter.Resources>
</ContentPresenter>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>

最佳答案

我相信当您将 Framework 元素放入 ContentControl 时,不会应用模板。如果您还将 TextBlock 样式声明为 Button 的资源,则它在两种情况下都适用。

<Window x:Class="WpfApplication1.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:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:local="clr-namespace:WpfApplication1"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="MainWindow"
Width="525"
Height="350"
mc:Ignorable="d">
<Window.Resources>
<Style x:Key="LinkButton"
BasedOn="{StaticResource ResourceKey={x:Type Button}}"
TargetType="Button">

<Setter Property="Width" Value="Auto" />

<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<ContentPresenter VerticalAlignment="Center"
Content="{TemplateBinding Content}"
ContentTemplate="{TemplateBinding ContentTemplate}" >
<ContentPresenter.Resources>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="TextDecorations" Value="Underline" />
</Style>
</ContentPresenter.Resources>
</ContentPresenter>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Window.DataContext>
<local:ViewModel />
</Window.DataContext>
<Grid x:Name="LayoutRoot">
<StackPanel>
<Button Style="{StaticResource LinkButton}">Text</Button>
<Button Style="{StaticResource LinkButton}">
<Button.Resources>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="TextDecorations" Value="Underline" />
</Style>
</Button.Resources>
<TextBlock Text="Text" />
</Button>
</StackPanel>
</Grid>
</Window>

关于wpf - 如何正确地将样式应用到内容展示器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13628101/

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