我想实现我的文本框的模板,显示在文本框右侧的小图像像它可以在里面ValidationTemplates实现:使用AdornedElementPlaceholder在正常的ContentTemplate
<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">
它不显示文本框本身。
我发现这个解决方法通过将控件模板代替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
+1,使用模板*改变控件的外观*,而不是简单地将多个元素组合在一起。 – 2014-10-29 15:10:23
好的,这就是我的想法,但是如果我将文本框包裹在我的控件中,我必须注册所有的文本框属性才能将它们绑定到我的控件中的实际文本框。这也有点难看... 我知道AdornedElementPlaceHolder是与Validation.ErrorTemplate结合使用的,但我认为对于这种用例可能有类似的方法。 – mikolaiguetschow 2014-10-29 21:39:45