【问题标题】:Do DataContext assign on XAML pointing to its code behind classDataContext 是否在 XAML 上分配指向其代码后面的类
【发布时间】:2014-02-10 12:40:52
【问题描述】:

我正在开发一个带有用户控件的 Windows Phone 8 应用程序。

在此用户控件上,我想在 XAML 上执行指向其代码隐藏的数据上下文。现在我在构造函数上做:

public CustomOptionButton()
{
    InitializeComponent();

    LayoutRoot.DataContext = this;
}

但是,如何在 XAML 上做到这一点?

【问题讨论】:

  • 如果您正在尝试创建一个可重用的组件,我不会使用 UserControl,我建议您创建一个自定义控件。这样你就可以使用 TemplateBinding

标签: silverlight xaml windows-phone-8


【解决方案1】:

试试这个:

<UserControl Name="LayoutRoot" 
             DataContext="{Binding RelativeSource={RelativeSource Self}}" ... />

或:

<UserControl.DataContext>
    <local:TestViewModel />
</UserControl.DataContext>

或:

<UserControl.Resources>
    <local:MyViewModel x:Key="TestViewModel" />
</UserControl.Resources>

<UserControl.DataContext>
    <Binding Source="{StaticResource TestViewModel}" />
</UserControl.DataContext>

【讨论】:

    【解决方案2】:

    当我在自定义控件中使用当前数据上下文时,这就是我正在做的事情:

    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    d:DataContext="{Binding}"
    

    编辑

    正如@WiredPrairie 指出的那样,我误解了这个问题,所以这是更简单的方法,并且可以替代@AnatoliyNikolaev 的建议

    x:Name="_this">  
    <Grid x:Name="LayoutRoot" DataContext="{Binding ElementName=_this}">
    

    【讨论】:

    • 这与所要求的不同。它只会从父控件绑定到已经建立的DataContext。问题是关于绑定到控件本身。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-24
    • 2011-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-26
    相关资源
    最近更新 更多