ControlTemplate用于将UIElements添加到原始控件

时间:2013-04-30 02:05:18

标签: wpf controltemplate uielement templatebinding

我想在内置TextBox的左侧添加感叹号图像,并在TextBox Validation.HasError附加属性为true时使其显示,否则将其隐藏。< / p>

如何在不重新绑定所有ControlTemplate属性的情况下使用TextBox添加图片?

<StackPanel>
    <StackPanel.Resources>
        <ControlTemplate x:Key="TextBoxWithIndicator" TargetType="{x:Type TextBox}">
            <StackPanel Orientation="Horizontal">
                <!-- Re-bind {Binding Path=Property}, including some that I may miss -->
                <TextBox Text="{TemplateBinding Text}" Width="{TemplateBinding Width}" Height="{TemplateBinding Height}"/>
                <Image Source="resources/exclaim.png" Visibility="{TemplateBinding Validation.HasError}"/>
            </StackPanel>
        </ControlTemplate>
    </StackPanel.Resources>
    <TextBox Template="{StaticResource TextBoxWithIndicator}" Width="120">Happy Go Lucky</TextBox>
</StackPanel>

注意前面的代码块代表了我到目前为止在WPF中的徒劳。它可能在几个方面也是错误的,例如: ValueConverter可能需要Visibility <--> Validation.HasError;尽管有TemplateBinding等,但在TextBox上设置Width="120"似乎调整了StackPanel宽度而不是TextBox宽度。

1 个答案:

答案 0 :(得分:0)

我建议调查Adorners。这些是特殊的FrameworkElements,在视觉元素之上的特殊Adorner层中呈现,旨在为用户提供视觉提示。

以上链接提供了Adorners的摘要以及自定义Adorner的示例。