繁体   English   中英

ContentControl中的Xaml并绑定到DependencyProperty

[英]Xaml inside ContentControl and binding to DependencyProperty

关于在Windows Phone上进行开发,我有两个问题:

我想创建自定义控件,并能够在其中提供一些额外的XAML。 所以我将ContentControlControlTemplate内部的ContentPresenter一起使用。

<ContentControl>
    <ControlTemplate>
        <TextBlock Name="TextBlockControl" Text="Existing controls"/>
        <ContentPresenter/>
    </ControlTemplate>
</ContentControl>

它有效,但是我无法从代码隐藏访问ControlTemplate内部的TextBlockControl FindName始终返回null。

其次,我想为控件提供属性,因此我创建了DependencyProperty,如下所示:

public string CustomText
{
    get { return (string)GetValue(CustomTextProperty); }
    set
    {
        SetValue(CustomTextProperty, value);
        TextBlockControl.Text = value;
    }
}

public static readonly DependencyProperty CustomTextProperty =
    DependencyProperty.Register("CustomText", typeof(string), typeof(MyControl), null);

如您所见,我编写了TextBlockControl.Text = value; 在我的控件内设置TextBlock的文本。 当我设置静态字符串时-它起作用

<MyControl CustomText="Static Text"/>

但是,当我想使用Binding (例如,针对LocalizedStrings资源)时,它不起作用。 我是否缺少PropertyMeta回调或某些IPropertyChanged继承? 我已经读过很多关于同一问题的StackOverflow问题,但是没有任何问题可以回答我的问题。

第一个问题的答案:

如果创建自定义控件并分配了模板,则可以使用以下命令访问该模板中的元素:

[TemplatePart(Name = "TextBlockControl", Type = typeof(FrameworkElement))]

您必须将此属性放入混合等工具,知道此自定义控件的模板必须具有一个称为TextBlockControl的文本块,然后从控件的OnApplyTemplate中可以引用它:

 protected override void OnApplyTemplate()
    {
        _part1 = this.GetTemplateChild("TextBlockControl") as FrameworkElement;
        base.OnApplyTemplate();
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM