我正在尝试为我的文本框实现一个模板,在文本框右侧显示一个小图片,就像在ValidationTemplates内部实现的那样:
<ControlTemplate x:Key="TextBoxTemplate">
<DockPanel>
<Grid x:Name="image" DockPanel.Dock="Right" Margin="3,0,0,0" Width="20" Height="20">
<Ellipse Width="20" Height="20" Fill="Red" />
<TextBlock Text="!" VerticalAlignment="Top" HorizontalAlignment="Center" FontWeight="Bold" Foreground="White" FontSize="16" TextAlignment="Center" Margin="7,-1" />
</Grid>
<AdornedElementPlaceholder />
</DockPanel>
</ControlTemplate>
但是当我尝试将TextBox.Template属性绑定到这个静态资源时:
<TextBox Template="{StaticResource TextBoxTemplate}" Text="Test">
它不会显示文本框本身。
我找到了一个解决方法,通过在ControlTemplate中放置另一个TextBox来代替AdornedElementPlaceholder,并将不同的值(文本、样式等)绑定到TemplatedParent:
<ControlTemplate x:Key="TextBoxTemplate">
<DockPanel DataContext="{Binding RelativeSource={RelativeSource TemplatedParent}}">
<Grid x:Name="image" DockPanel.Dock="Right" Margin="3,0,0,0" Width="20" Height="20">
<Ellipse Width="20" Height="20" Fill="Red" />
<TextBlock Text="!" VerticalAlignment="Top" HorizontalAlignment="Center" FontWeight="Bold" Foreground="White" FontSize="16" TextAlignment="Center" Margin="7,-1" />
</Grid>
<TextBox Text="{Binding Text}" Style="{Binding Style}" Width="{Binding Width}" Height="{Binding Height}" />
</DockPanel>
</ControlTemplate>
然而这是一种相当丑陋的方法,因为必须显式绑定每个属性。
是否有另一种更简单的方法? ValidationTemplate 中的 AdornedElementPlaceholder 是如何实现的?我能否将其用于我的 ContentTemplate 中?
谢谢, Ialokim