【问题标题】:How to change the parent of DataContext in xaml in Windows phone 8.1如何在 Windows phone 8.1 中更改 xaml 中 DataContext 的父级
【发布时间】:2014-10-20 17:53:22
【问题描述】:

我在 windows phone 8.1 中有这个 xaml。 我的页面数据上下文绑定到 ViewModel,即 VM。 我的 listView 绑定到 ViewModel 的 Items。 并且每个列表视图项中的文本都绑定到 ViewModel 的项的文本。

<Page DataContext="{Binding VM}">
<ListView ItemsSource="{Binding Items}">
     <ListView.ItemTemplate>
        <DataTemplate>
                <TextBox Text="{Binding Text}"/>
                <TextBox Text="{Binding soemthing in VM}" />
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>
</Page>

我的问题是如何更改我的第二个文本框的父数据上下文,以便我可以在我的 ViewModel(不是我的 ViewModel.Items)中绑定一些东西?

谢谢。

【问题讨论】:

  • 基本上,你不能——不幸的是,WP Silverlight 不支持RelativeSource Mode=FindAncestor。必须使用解决方法。你想绑定什么? (字符串?刷子?另一个集合?)
  • 你总是可以使用依赖注入。将您实际想要的绑定的引用注入到 Item ViewModel
  • 我正在尝试绑定到我的 ViewModel 中的 RelayCommand。 AFAIK,RelayCommand 应该在 ViewModel 中,所以我不能把它放在我的项目中。
  • 如何使用依赖注入将其绑定到视图模型?
  • 这意味着,将对 RelayCommand 的引用传递给每个项目,并将其作为属性公开——然后您可以绑定到它。这并不理想,但可能是最好的选择。

标签: xaml data-binding windows-phone


【解决方案1】:

如果你不介意元素绑定,

<ListView ItemsSource="{Binding Items}">
    <ListView.ItemTemplate>
        <DataTemplate>
            <TextBox Text="{Binding Text}"/>


            <!-- Bind the DataContext directly to the whatever element you like, in this case the page, then the Text Binding is basically the DataContext.VM_Property -->
            <TextBlock Text="{Binding DataContext.VM_Property}" DataContext="{Binding ElementName=page}" ></TextBlock>

        </DataTemplate>

    </ListView.ItemTemplate>
</ListView>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-23
    • 1970-01-01
    • 2010-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-28
    • 1970-01-01
    相关资源
    最近更新 更多