简体   繁体   中英

Xaml inside ContentControl and binding to DependencyProperty

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 (eg 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.

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();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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