ContentControl 内的 Xaml 并绑定到 DependencyProperty
我有两个关于在 Windows Phone 上开发的问题:
I have two questions about developing at Windows Phone:
我想创建自定义控件并能够在其中提供一些额外的 XAML.所以我在 ControlTemplate
中使用 ContentControl
和 ContentPresenter
.
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>
它有效,但我无法从代码隐藏访问 ControlTemplate
内的 TextBlockControl
.FindName
总是返回 null.
It worked, but I can't access TextBlockControl
inside ControlTemplate
from code-behind. FindName
always returns null.
其次,我想为 Control 提供属性,所以我像这样创建 DependencyProperty:
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);
如您所见,我编写了 TextBlockControl.Text = value;
来为控件内的 TextBlock 设置文本.当我设置静态字符串时 - 它有效
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"/>
但是当我想使用 Binding
(例如对于 LocalizedStrings
资源)时 - 它不起作用.我是否缺少 PropertyMeta 回调或某些 IPropertyChanged 继承?我已经阅读了大量关于相同问题的 * 问题,但没有人回答我的问题.
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 * questions with the same issue, but nothing answered my questions.
第一个问题的答案:
如果您创建自定义控件并分配模板,则可以使用以下方法访问该模板中的元素:
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))]
你必须把这个属性放在像blend这样的工具中,知道这个自定义控件的模板必须有一个名为TextBlockControl的文本块.然后从控件的OnApplyTemplate你应该得到一个对它的引用:
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();
}