在 Windows 通用应用程序中绑定到 xaml 页面的 DataContext

Binding to xaml page's DataContext in Windows Universal App

我正在使用内容对话框在网格中的项目被选中时显示实例数据。

在调用页面的视图模型中,选择项目时将执行以下方法。

public virtual void ItemSelected(object sender, object parameter)
{
    var arg = parameter as Windows.UI.Xaml.Controls.ItemClickEventArgs;
    var clickedItem = arg.ClickedItem;
    var item = clickedItem as ItemsModel;

    var dialog = new ItemsDialog();
    dialog.DataContext = item;
    dialog.ShowAsync();
}

这显示了对话框,并且内容按预期显示。现在,我正尝试将我的 xaml 拆分为不同的模板,并尝试使用 ContentControl 来显示适当的模板。我写了一个 DataTemplateSelector 来帮助选择正确的模板,但现在我无法弄清楚 ContentControl 的数据绑定(请参阅下面的简化版本)。

<ContentDialog.Resources>
    <UI:MyTemplateSelector x:Key="MyTemplateSelector"
            Template1="{StaticResource Template1}"
            Template2="{StaticResource Template2}"/>

    <DataTemplate x:Key="Template1"/>
    <DataTemplate x:Key="Template2"/>
</ContentDialog.Resources>

<StackPanel>
    <ContentControl DataContext="{Binding}"
        ContentTemplateSelector="{StaticResource MyTemplateSelector}"/>
</StackPanel>

调试我的 ContentTemplateSelector 时,我的绑定始终是 null。我尝试过各种形式的绑定语法,但没有成功。如何将 ContentControlDataContext 正确设置为 ContentDialogDataContext

您还必须绑定内容。

Content="{Binding}"

您已经有了数据源 (DataContext) 和数据的显示方式(模板),现在您需要指定哪些属性将它们组合在一起。

When debugging into my ContentTemplateSelector, my binding is always null

您需要为ContentControl控件的Content属性设置数据绑定,见MSDN中的备注:

The Content property of a ContentControl can be any type of object, such as a string, a UIElement, or a DateTime. By default, when the Content property is set to a UIElement, the UIElement is displayed in the ContentControl. When Content is set to another type of object, a string representation of the object is displayed in the ContentControl.

所以下面的 xaml 应该有效:

<StackPanel>
    <ContentControl Content="{Binding}"
        ContentTemplateSelector="{StaticResource MyTemplateSelector}"/>
</StackPanel>

Github

中查看我完成的示例