将ControlTemplate子项绑定到自定义控件上的DependencyProperty上不起作用

问题描述 投票:0回答:1

我的用户控件看起来像这样

    <UserControl.Resources>
    <Style TargetType="TextBox" x:Key="ExtendeTextBoxStyle">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="TextBox">
                    <Grid>

                        <TextBlock Grid.Row="3" Text="{Binding ErrorMessage, RelativeSource={RelativeSource TemplatedParent}}"  x:Name="ErrorMessage" Foreground="Red" ></TextBlock>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</UserControl.Resources>
<Grid>
    <TextBox x:Name="textbox"   Style="{StaticResource ExtendeTextBoxStyle}" ></TextBox>
</Grid>

后面的代码

 public string ErrorMessage
    {
        get { return (string)GetValue(ErrorMessageProperty); }
        set { SetValue(ErrorMessageProperty, value); }
    }

    // Using a DependencyProperty as the backing store for ErrorMessage.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty ErrorMessageProperty =
        DependencyProperty.Register("ErrorMessage", typeof(string), typeof(CustomControl), new PropertyMetadata("x"));

现在在我的主页上,我试图像这样传递ErrorMessage的值

 <local:CustomControl ErrorMessage="My Error message"></local:CustomControl>

对我来说一切看起来不错,但没有显示ErrorMessage值。我在这里想念什么?

我的完整应用程序可供here检查

wpf xaml uwp dependency-properties
1个回答
0
投票

[RelativeSource TemplatedParent是错误的,因为ErrorMessage不是模板化TextBox的属性。

使用此:

Text="{Binding ErrorMessage, RelativeSource={RelativeSource AncestorType=UserControl}}"
© www.soinside.com 2019 - 2024. All rights reserved.