【问题标题】:Binding ControlTemplate child to DependencyProperty on a custom control not working将 ControlTemplate 子绑定到自定义控件上的 DependencyProperty 不起作用
【发布时间】:2020-09-01 17:36:21
【问题描述】:

我的用户控件如下所示:

    <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查看。

【问题讨论】:

    标签: c# xaml uwp dependency-properties


    【解决方案1】:

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

    像这样使用 ElementName 绑定

    <UserControl x:Name="self" ...>
    
    <TextBlock Text="{Binding ErrorMessage, ElementName=self}" .../>
    

    ControlTemplate 中的绑定通常是 TemplateBindings 之类的

    <TextBlock Text="{TemplateBinding Text}" .../>
    

    您可以设置样式 TextBox 的 Text 属性,例如

    <TextBox Style="{StaticResource ExtendeTextBoxStyle}"
             Text="{Binding ErrorMessage, ElementName=self}" .../>
    

    【讨论】:

    • 给我一个错误 --> 元素 'RelativeSource' 上的未知成员 'AncestorType'
    • 这是 UWP,对吧?请不要用 WPF 标记 UWP 问题。
    • 对不起。我的错。现已更正
    • 你忘了&lt;UserControl x:Name="CustomControl" ...&gt;
    • 在调试过程中,您应该已经在 Visual Studio 的输出窗口中看到了数据绑定错误消息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-07
    • 1970-01-01
    • 2019-07-27
    • 1970-01-01
    • 1970-01-01
    • 2012-04-15
    • 2011-08-06
    相关资源
    最近更新 更多