C# 绑定到相应样式的控件属性
我想为文本框定义一个样式,并在该样式中绑定到应用相应样式的特性。大概是这样的:C# 绑定到相应样式的控件属性,c#,wpf,xaml,data-binding,binding,C#,Wpf,Xaml,Data Binding,Binding,我想为文本框定义一个样式,并在该样式中绑定到应用相应样式的特性。大概是这样的: <Style TargetType="{x:Type TextBox}" BasedOn="{StaticResource {x:Type TextBox}}"> <Style.Triggers> <Trigger Property="IsEnabled" Value="True">
<Style TargetType="{x:Type TextBox}" BasedOn="{StaticResource {x:Type TextBox}}">
<Style.Triggers>
<Trigger Property="IsEnabled" Value="True">
<Setter Property="ToolTip">
<Setter.Value>
<TextBlock Text="{Binding ????Bind to the textbox TEXT property????}">
</TextBlock>
</Setter.Value>
</Setter>
</Trigger>
</Style.Triggers>
</Style>
这可能吗
这里是完整的窗口:
<Window x:Class="StyleBinding.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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:StyleBinding"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.Resources>
<Style TargetType="{x:Type TextBox}" BasedOn="{StaticResource {x:Type TextBox}}">
<Style.Triggers>
<Trigger Property="IsEnabled" Value="True">
<Setter Property="ToolTip">
<Setter.Value>
<TextBlock Text="{Binding Text, RelativeSource={RelativeSource Self}}"/>
</Setter.Value>
</Setter>
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
<Grid>
<TextBox HorizontalAlignment="Left" Height="34" Margin="235,140,0,0" TextWrapping="Wrap" IsEnabled="True"
Text="Just a simple text" VerticalAlignment="Top" Width="284">
</TextBox>
</Grid>
</Window>
您只需使用
相对资源
绑定即可访问文本框
的文本
属性
<Setter Property="ToolTip" Value="{Binding Text, RelativeSource={RelativeSource Self}}"/>
如果您以自己的样式构建自定义工具提示模板,可以这样做
<Style TargetType="{x:Type TextBox}" BasedOn="{StaticResource {x:Type TextBox}}">
<Setter Property="ToolTip">
<Setter.Value>
<ToolTip>
<TextBlock Text="{Binding PlacementTarget.Text, RelativeSource={RelativeSource AncestorType={x:Type ToolTip}}}"/>
</ToolTip>
</Setter.Value>
</Setter>
</Style>
工具提示的PlacementTarget
是此处的文本框。以下是一个工作示例:
<Style BasedOn="{StaticResource {x:Type TextBox}}" TargetType="{x:Type TextBox}">
<Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self}, Path=Text}" />
</Style>
关键是使用RelativeSource
绑定Self
无需在启用的上设置触发器,因为默认情况下,工具提示将仅在启用的控件上显示。谢谢,我想我的问题是我的工具提示是textblock:所以它使用的是textblock,而不是textbox本身。在这种情况下,如何绑定到父文本框?