gpt4 book ai didi

c# - 文本框上的 XAML 控件模板,文本框上的数据触发器

转载 作者:太空宇宙 更新时间:2023-11-03 23:30:04 24 4
gpt4 key购买 nike

我已经创建了一个自定义 TextBox,我想为其设置样式,并向此 TextBox 添加水印。我想在 TextBox 为空时添加水印,这种可见性只能从我的 Style 中设置。这是我的风格:

<Style TargetType="{x:Type textboxes:CustomTextBox}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type textboxes:CustomTextBox}">
<Grid>
<Border Name="Border"
CornerRadius="2"
Padding="2"
Background="DeepPink"
BorderBrush="Green"
BorderThickness="1">
<Grid>
<ScrollViewer Margin="0"
x:Name="PART_ContentHost" />
<TextBlock IsHitTestVisible="False"
Text="WATERMARK!"
Foreground="White"
VerticalAlignment="Center"
HorizontalAlignment="Left"
Margin="10,0,0,0">
<TextBlock.Style>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Visibility"
Value="Collapsed" />
<Style.Triggers>
<DataTrigger Binding="{Binding Text, ElementName=PART_ContentHost}"
Value="">
<Setter Property="Visibility"
Value="Visible" />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style></TextBlock>
</Grid>
</Border>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>

样式按预期应用,但我很难在 TextBlock 中定义 DataTrigger 绑定(bind)。我应该绑定(bind)什么?

最佳答案

您应该改用 ControlTemplate 触发器。您需要检查文本是否为空以及文本框是否没有焦点,因此需要多重触发:

这是我使用 Tag 属性指定水印文本的水印文本框样式:

<Style x:Key="WatermarkTextBox" TargetType="TextBox" BasedOn="{StaticResource {x:Type TextBox}}">
<Setter Property="Tag" Value="Enter Text" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="TextBox">
<Grid>
<Border x:Name="border" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="True">
<ScrollViewer x:Name="PART_ContentHost" Focusable="False" HorizontalScrollBarVisibility="Hidden" VerticalScrollBarVisibility="Hidden"/>
</Border>

<TextBlock x:Name="Watermark" Text="{TemplateBinding Tag}"
Visibility="Collapsed" IsHitTestVisible="False" Opacity="0.5"
Foreground="{TemplateBinding Foreground}"
Margin="{TemplateBinding BorderThickness}" Padding="{TemplateBinding Padding}"
HorizontalAlignment="Stretch"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
TextAlignment="{TemplateBinding TextAlignment}"/>
</Grid>
<ControlTemplate.Triggers>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="IsKeyboardFocusWithin" Value="False" />
<Condition Property="Text" Value="" />
</MultiTrigger.Conditions>
<Setter TargetName="Watermark" Property="Visibility" Value="Visible" />
</MultiTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>

关于c# - 文本框上的 XAML 控件模板,文本框上的数据触发器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32624024/

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