UserControl嵌入免费的XAML内容

时间:2014-02-10 16:56:07

标签: winrt-xaml

我想创建一个可以嵌入免费内容的用户控件。

我为内容创建了一个Dependency属性:

public sealed partial class MyUserControl : UserControl
{

    public Border MyProperty
    {
        get { return (Border)GetValue(MyPropertyProperty); }
        set { SetValue(MyPropertyProperty, value); }
    }

    public static readonly DependencyProperty MyPropertyProperty =
        DependencyProperty.Register("MyProperty", typeof(Border), typeof(VisitList), new PropertyMetadata(new Border() { Height=300, Width=300 }));

...
}

所以在我的MainPage.xaml中,我可以使用以下代码:

 <MyUserControl>
            <MyUserControl.MyProperty>
                <Border x:Name="MyContent" Width="60" Height="60" Background="Pink">
                    ... Whatever ...
                </Border>
            </MyUserControl.MyProperty>                
 </MyUserControl>

由此,我无法找到MyUserControl.xaml中的XAML语法,用于声明将在运行时由MyContent替换的占位符。 我尝试过:

<UserControl ... >
....
    <Grid ...>

         <ContentPresenter Content="{TemplateBinding MyProperty}" />

    </Grid>
</UserControl>

但是,它与消息崩溃了:

An exception of type 'Windows.UI.Xaml.Markup.XamlParseException' occurred in xXx.exe but was not handled in user code
WinRT information: Failed to create a 'Windows.UI.Xaml.DependencyProperty' from the text 'MyProperty'. [Line: 29 Position: 35]

(The Line:29 Position:35指Content =“{TemplateBinding MyProperty}”)

1 个答案:

答案 0 :(得分:1)

听起来你正在混合Templated Controls和UserControls。它有点复杂,但基本上,当TemplateBindings与控件的ContentTemplate分开时,它就会起作用,而不是内容本身(我认为这是基于你所展示的xaml而发生的事情)。

尝试以这种方式更改绑定:

<UserControl x:Name="RootControl" ...>
....
    <ContentControl Content="{Binding MyProperty, ElementName=RootControl}" />
....
</UserControl>

这意味着您需要让UserControl实现INotifyPropertyChanged,以防它需要响应更改Content