gpt4 book ai didi

wpf - 如何从 wpf 中的样式绑定(bind)到标签?

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

我正在实现一个搜索文本框;你能帮我绑定(bind)到 TextBox.Tag 吗?

风格

<Style x:Key="SearchTextBox" TargetType="{x:Type TextBox}">
<Style.Resources>
<VisualBrush x:Key="CueBannerBrush" AlignmentX="Left" AlignmentY="Center" Stretch="None">
<VisualBrush.Visual>
<Label Content="{Binding RelativeSource={RelativeSource Mode=Self}, Path=Tag}" Foreground="{StaticResource SearchTextBox.Foreground}" FontSize="{StaticResource SearchTextBox.FontSize}"/>
</VisualBrush.Visual>
</VisualBrush>
</Style.Resources>
<Setter Property="FontSize" Value="{StaticResource SearchTextBox.FontSize}" />
<Setter Property="Foreground" Value="{StaticResource SearchTextBox.TextForeground}" />
<Setter Property="MinWidth" Value="200" />
<Style.Triggers>
<Trigger Property="Text" Value="{x:Static sys:String.Empty}">
<Setter Property="Background" Value="{StaticResource CueBannerBrush}" />
</Trigger>
<Trigger Property="Text" Value="{x:Null}">
<Setter Property="Background" Value="{StaticResource CueBannerBrush}" />
</Trigger>
<Trigger Property="IsKeyboardFocused" Value="True">
<Setter Property="Background" Value="White" />
</Trigger>
</Style.Triggers>
</Style>

用法

<TextBox Style="{StaticResource SearchTextBox}" Tag="Search templates" />

如何让绑定(bind)生效?

最佳答案

这里的这篇文章与你的极其相似:WPF Bind to parent property from within nested element using style

虽然它并没有真正提供代码示例,但您可以使用这里的一些 xaml 作为当前方法的替代方法。

<Style x:Key="SearchTextBox" BasedOn="{StaticResource {x:Type TextBox}}" TargetType="{x:Type TextBox}">
<Style.Setters>
<Setter Property="Tag" Value=""/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TextBox}">
<Grid>
<ScrollViewer x:Name="PART_ContentHost" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" />
<TextBlock x:Name="textBlock" Opacity="0.345" Text="{TemplateBinding Tag}" TextWrapping="Wrap" Visibility="Hidden" />
</Grid>
<ControlTemplate.Triggers>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="IsFocused" Value="False" />
<Condition Property="Text" Value="" />
</MultiTrigger.Conditions>
<Setter Property="Visibility" TargetName="textBlock" Value="Visible" />
</MultiTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style.Setters>
</Style>

而且您仍将按照您已有的方式编写文本框代码:

<TextBox Style="{StaticResource SearchTextBox}" Tag="Search templates" />

关于wpf - 如何从 wpf 中的样式绑定(bind)到标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13334943/

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