【问题标题】:Bind to parent datacontext (out of itemsource)绑定到父数据上下文(超出 itemssource)
【发布时间】:2014-06-07 08:27:56
【问题描述】:

在我的 Windows Phone 8 应用程序中,我有项目列表。我已经为列表项定义了 ItemTemplate。

我想在每个项目中显示一个来自视图模型的值,而不是来自列表项目本身的值。我应该如何设置从列表项到视图模型的绑定。

我的数据模板是这样的:

<DataTemplate x:Key="template">
    <StackPanel>
        <TextBlock Text="{Binding Name}"/> <!-- From list item -->
        <TextBlock Text="{Binding MyViewModel.Country ?? }"/> <!-- From view model -->
    </StackPanel>  
</DataTemplate>

那么如何将 Country 属性绑定到视图模型,而不是列表项(在项源中)。

【问题讨论】:

标签: wpf windows-phone-8 mvvm binding caliburn.micro


【解决方案1】:

既然你用 WPF 标记了你的问题,我可以告诉你在 WPF 中的做法,你可以验证它是否可以在 Windows phone 8 应用程序中重复使用。

首先,您可以将 x:Name 赋予 ViewModel 绑定到的根元素。假设它是窗口,在其上设置 x:Name 并使用 ElementName 进行绑定。

<Window x:Name="myWindow">
  ...
  <DataTemplate x:Key="template">
    <StackPanel>
        <TextBlock Text="{Binding Name}"/> <!-- From list item -->
        <TextBlock Text="{Binding DataContext.MyViewModel.Country,
                            ElementName=myWindow }"/> <!-- From view model -->
    </StackPanel>  
</DataTemplate>
</Window>

第二,你可以尝试使用RelativeSource遍历Visual tree并获取根元素DataContext。

<DataTemplate x:Key="template">
    <StackPanel>
        <TextBlock Text="{Binding Name}"/> <!-- From list item -->
        <TextBlock Text="{Binding DataContext.MyViewModel.Country,
                           RelativeSource={RelativeSource Mode=FindAncestor, 
                                                   AncestorType=Window} }"/>
                         <!-- From view model -->
    </StackPanel>  
</DataTemplate>

此外,如果 ListBox 从根元素继承 DataContext(即,您没有在 ListBox 上显式设置 DataContext)。您也可以在 ListBox 上使用这两种方法来代替 Window。

注意 - 正如提到的hereFindAncestor 没有为 Windows phone 8 定义,但元素名称确实有效。所以,尝试使用第一种方法,它应该适合你。

【讨论】:

  • 非常感谢罗希特!我使用caliburn micro,看起来我在没有指定视图模型的情况下进行了绑定。所以这个对我有用 {Binding DataContext.Country, ElementName=myWindow}
  • ElementName 使模板不可重用,并且 FindAncestor 在 WinRT/Windows 应用商店应用程序中不存在。如何在 Windows Store Apps 中绑定父上下文?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-23
  • 2015-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-24
相关资源
最近更新 更多