在普通的ContentTemplate中使用AdornedElementPlaceholder

3

我正在尝试为我的文本框实现一个模板,在文本框右侧显示一个小图片,就像在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

1个回答

1
你的错误在于没有正确使用AdornedElementPlaceholderValidation.ErrorTemplate。在这种情况下,它会将原始控件放置在AdornedElementPlaceholder的位置。
如果你使用Template,则不会自动采用原始控件,你需要定义完整的模板。
我建议,如果你只是想将几个控件简单地组合成一个,那么最好创建一个普通的UserControl,这比处理完整的模板要简单得多。

+1,使用模板来更改控件的外观,而不是简单地组合多个元素。 - Mike Strobel
好的,这就是我想到的,但如果我将TextBox包装在我的自定义控件中,我必须注册所有的文本框属性,以便将它们绑定到我的控件内部的实际文本框。这也有点丑陋... 我知道AdornedElementPlaceHolder是为与Validation.ErrorTemplate一起使用而设计的,但我认为可能有类似于这种用例的方法。 - mikolaiguetschow

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接