简体   繁体   English

ContentControl中的Xaml并绑定到DependencyProperty

[英]Xaml inside ContentControl and binding to DependencyProperty

I have two questions about developing at Windows Phone: 关于在Windows Phone上进行开发,我有两个问题:

I want to create custom control and be able to provide some extra XAML inside it. 我想创建自定义控件,并能够在其中提供一些额外的XAML。 So I use ContentControl with ContentPresenter inside ControlTemplate . 所以我将ContentControlControlTemplate内部的ContentPresenter一起使用。

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

It worked, but I can't access TextBlockControl inside ControlTemplate from code-behind. 它有效,但是我无法从代码隐藏访问ControlTemplate内部的TextBlockControl FindName always returns null. FindName始终返回null。

Secondly, I want to provide attributes for Control, so I create DependencyProperty like this: 其次,我想为控件提供属性,因此我创建了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);

As you can see, I write TextBlockControl.Text = value; 如您所见,我编写了TextBlockControl.Text = value; to set text for TextBlock inside of my Control. 在我的控件内设置TextBlock的文本。 When I set static string - it works 当我设置静态字符串时-它起作用

<MyControl CustomText="Static Text"/>

But when I want to use Binding (eg for LocalizedStrings resource) - it doesn't work. 但是,当我想使用Binding (例如,针对LocalizedStrings资源)时,它不起作用。 Am i missing PropertyMeta Callback, or some IPropertyChanged inheritance? 我是否缺少PropertyMeta回调或某些IPropertyChanged继承? I have read tons of StackOverflow questions with the same issue, but nothing answered my questions. 我已经读过很多关于同一问题的StackOverflow问题,但是没有任何问题可以回答我的问题。

the answer to the first question : 第一个问题的答案:

If you créate your custom-control, and you assign a template, you can Access to the elements in that template using : 如果创建自定义控件并分配了模板,则可以使用以下命令访问该模板中的元素:

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

You have to put this attribute in order to tools like blend, know that the template for this custom-control has to have a textblock called TextBlockControl.Then from the control's OnApplyTemplate you should get a reference to it whit : 您必须将此属性放入混合等工具,知道此自定义控件的模板必须具有一个称为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