【问题标题】:Xaml inside ContentControl and binding to DependencyPropertyContentControl 中的 Xaml 并绑定到 DependencyProperty
【发布时间】:2013-11-06 20:47:37
【问题描述】:

我有两个关于在 Windows Phone 上开发的问题:

我想创建自定义控件并能够在其中提供一些额外的 XAML。所以我在ControlTemplate 中使用ContentControlContentPresenter

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

它有效,但我无法从代码隐藏中访问 ControlTemplate 内的 TextBlockControlFindName 总是返回 null。

其次,我想为 Control 提供属性,所以我这样创建 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 问题,但没有一个回答我的问题。

【问题讨论】:

    标签: c# xaml windows-phone


    【解决方案1】:

    第一个问题的答案:

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

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

    你必须把这个属性放在像混合这样的工具上,知道这个自定义控件的模板必须有一个名为 TextBlockControl 的文本块。然后从控件的 OnApplyTemplate 你应该得到一个对它的引用:

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

    【讨论】:

    • 谢谢,稍后我会检查的。顺便说一句,你知道吗,如果 ControlTemplate 是将用户 XAML 插入控件的 XAML 的唯一可能方法?
    • 嗨 Wayne,在 .NET 中有两种创建控件的方法。用户控件或自定义控件。用户控件是当您想要将多个控件混合到一个控件中时,以便在您的应用程序中重用它。自定义控件通常继承自现有控件,如 GridView、StackPanel、Button...,以增强其行为。也许对您来说最好的方法是从用户控件开始。希望对您有所帮助!
    • 用户控件不适合我的目的。我想在外部添加额外的 XAML,而不仅仅是组控件
    • 您的代码有效,谢谢!但是现在我无法访问我传递给控件的元素,它们在代码隐藏中可见,但它们都是空的。
    • 我只能使用 XAML 中的 Loaded 事件然后将 sender 转换为其类型来访问它们。这太糟糕了。
    猜你喜欢
    • 1970-01-01
    • 2017-01-28
    • 1970-01-01
    • 2019-09-07
    • 1970-01-01
    • 1970-01-01
    • 2013-06-03
    • 1970-01-01
    相关资源
    最近更新 更多