Xaml inside ContentControl and binding to DependencyProperty

≯℡__Kan透↙ 提交于 2019-12-11 19:43:39

问题


I have two questions about developing at Windows Phone:

I want to create custom control and be able to provide some extra XAML inside it. So I use ContentControl with ContentPresenter inside ControlTemplate.

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

It worked, but I can't access TextBlockControl inside ControlTemplate from code-behind. FindName always returns null.

Secondly, I want to provide attributes for Control, so I create DependencyProperty like this:

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; to set text for TextBlock inside of my Control. When I set static string - it works

<MyControl CustomText="Static Text"/>

But when I want to use Binding (e.g. for LocalizedStrings resource) - it doesn't work. Am i missing PropertyMeta Callback, or some IPropertyChanged inheritance? I have read tons of StackOverflow questions with the same issue, but nothing answered my questions.


回答1:


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 :

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


来源:https://stackoverflow.com/questions/19809073/xaml-inside-contentcontrol-and-binding-to-dependencyproperty

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!