【问题标题】:Binding of TextBlock inside Custom Control to dependency property of the same Custom Control将自定义控件内的 TextBlock 绑定到同一自定义控件的依赖属性
【发布时间】:2010-12-23 17:17:43
【问题描述】:

我有一个自定义控件,里面有一个 TextBlock:

<Style TargetType="{x:Type local:CustControl}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type local:CustControl}">
                <Border Background="Blue"
                        Height="26" 
                        Width="26" Margin="1">

                        <TextBlock x:Name="PART_CustNo"
                                   FontSize="10"
                                   Text="{Binding Source=CustControl,Path=CustNo}" 
                                   Background="PaleGreen" 
                                   Height="24" 
                                   Width="24"
                                   Foreground="Black">
                        </TextBlock>

                </Border>
             </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

而且这个自定义控件有一个依赖属性:

    public class CustControl : Control
{
    static CustControl()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(CustControl), new   FrameworkPropertyMetadata(typeof(CustControl)));
    }

    public readonly static DependencyProperty CustNoProperty = DependencyProperty.Register("CustNo", typeof(string), typeof(CustControl), new PropertyMetadata(""));

    public string CustNo
    {
        get { return (string)GetValue(CustNoProperty); }
        set { SetValue(CustNoProperty, value); }
    }

}

我希望在自定义控件的每个实例中将“CustNo”属性的值转移到 TextBlock 的“文本”属性中。 但我的:

Text="{Binding Source=CustControl,Path=CustNo}"

不工作。

不适用于 Path=CustNoProperty:

Text="{Binding Source=CustControl,Path=CustNoProperty}"

【问题讨论】:

    标签: c# wpf data-binding xaml custom-controls


    【解决方案1】:

    你需要一个 TemplateBinding,比如

    <TextBlock
       Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=CustNo}" />
    

    【讨论】:

    【解决方案2】:

    试试这个SO question 的答案。我想你会想要第三个例子。即:

    {Binding Path=CustNo, RelativeSource={RelativeSource TemplatedParent}}
    

    【讨论】:

    • 西蒙,谢谢。你的回答就是我所需要的。很抱歉,无法选择几个相同的正确答案,这些答案是在同时被接受的时候发布的。
    • 好吧,我的答案比 Ian 早 2 分钟发布,但您必须当时在场才能注意到。无压力。也许下次……
    猜你喜欢
    • 1970-01-01
    • 2019-05-26
    • 2012-08-07
    • 2012-08-29
    • 1970-01-01
    • 2011-05-08
    • 2011-03-24
    • 1970-01-01
    • 2021-08-17
    相关资源
    最近更新 更多