【发布时间】:2016-10-26 00:50:18
【问题描述】:
重新编写问题以阐明我的需求:
我想在 Textboxes 为空时添加预览文本,就像你们中的一些人可能从 Xamarin 知道的一样。
我在SO 上找到了这个答案。
这是我上面链接的答案中的Style。
<TextBlock Grid.Row="5"
Grid.Column="1"
VerticalAlignment="Center"
Text="Username:">
</TextBlock>
<TextBox Grid.Row="5"
Grid.Column="3">
<TextBox.Style>
<Style TargetType="TextBox">
<Style.Resources>
<VisualBrush x:Key="CueBannerBrush" AlignmentX="Left" AlignmentY="Center" Stretch="None">
<VisualBrush.Visual>
<Label Content="Test" Foreground="LightGray" />
</VisualBrush.Visual>
</VisualBrush>
</Style.Resources>
<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>
</TextBox>
我得到以下结果:
由于它运行良好,我想将它应用到该Window 中的每个TextBox。
所以我的方法是改变这一行:
<Label Content="Test" Foreground="LightGray" />
我认为也许将其更改为 <Label Content="Test" Foreground="LightGray" /> 可以解决问题,但它不起作用。
我猜这与 Tag 属性和它的 Type (object instead of string) 有关。
由于第一种方法很有效,我真的不明白为什么我需要一个自定义控件...
所以我当时尝试的是这样的:
<Window.Resources>
<Style TargetType="TextBox">
<Style.Resources>
<VisualBrush x:Key="CueBannerBrush" AlignmentX="Left" AlignmentY="Center" Stretch="None">
<VisualBrush.Visual>
<Label Content="{Binding RelativeSource={RelativeSource Self}, Path=Tag}" Foreground="LightGray" />
</VisualBrush.Visual>
</VisualBrush>
</Style.Resources>
<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>
</Window.Resources>
我错过了什么 - 为什么这不起作用?
【问题讨论】:
-
如果你想使用这种特定的方式,只需给样式模板一个
x:Key名称并将其放在资源字典中,然后全局设置或在实例中使用它,如<TextBox Style="{StaticResource StyleTemplateKeyName}"/> -
Ayyappan Subramanian 表示 VisualBrush 中的绑定需要一些帮助才能找到 DataContext。他使用他的 Temp 类(例如BindingProxy)解决了这个问题。
-
@Funk 所以这意味着没有自定义控件是不可能的? - 另请注意,如果有没有 VisualBrush 的完全不同的解决方案,我想听听。
-
“为什么这不起作用?”因为RelativeSource 绑定会将标签的标签放入标签内容中,所以您需要标签中的文本框标签。但是你不会得到它,因为标签上方没有 VisualTree。
标签: c# wpf xaml binding textbox