Listbox DataTemplate字段绑定不起作用

时间:2014-03-03 12:03:34

标签: wpf mvvm

我有一个雇员实体列表,绑定到实现DataTemplate的列表框。

的DataTemplate:

<DataTemplate x:Key="EmployeeTemplate">
 <Grid>
  <Grid.ColumnDefinitions>
   <ColumnDefinition Width="*"/>
   <ColumnDefinition Width="*"/>
  </Grid.ColumnDefinitions>
  <StackPanel Grid.Column="0" Orientation="Vertical" 
              VerticalAlignment="Top" Margin="2">
   <TextBlock Foreground="Black" FontSize="12"
              VerticalAlignment="Bottom" Text="{Binding Path=Test}">
   </TextBlock>
   <TextBlock Foreground="Black" FontSize="12"
              VerticalAlignment="Bottom" Text="{Binding Path=Language.ContactNumber}">
   </TextBlock>
  </StackPanel>
  <StackPanel Grid.Column="1" Orientation="Vertical" 
              VerticalAlignment="Top" Margin="2">
   <TextBlock Foreground="Black" FontSize="12"
              VerticalAlignment="Bottom" Text="{Binding Path=IdNumber}">
   </TextBlock>
   <TextBlock Foreground="Black" FontSize="12"
              VerticalAlignment="Bottom" Text="{Binding Path=ContactNumber}">
   </TextBlock>
  </StackPanel>
 </Grid>
</DataTemplate>

列表框:

<ListBox ItemsSource="{Binding Path=Employees}"  
         x:Name="ListBoxEmployees" 
         ItemTemplate="{DynamicResource EmployeeTemplate}" 
         BorderBrush="DarkGray" 
         Margin="5"/>

我的Datacontext是一个名为EmployeeViewModel的viewModel,它包含员工的集合。这种绑定工作正常,员工得到展示,一切都很好。问题是EmployeeViewModel继承自包含名为Language的静态属性的基本抽象ViewModel。这个模型有各种字段,我将标签绑定到整个应用程序。数据模板中的值不起作用。为什么呢?

其他信息:此列表框位于mainwindow.xaml

上的用户控件中

编辑:

 xmlns:viewModels="clr-namespace:POC.DesktopClient.ViewModels"
        mc:Ignorable="d"
        d:DataContext="{d:DesignInstance viewModels:EmployeeViewModel}"

我的usercontrol顶部的这些XML命名空间在绑定时允许xaml intelisense。知识确实会获取语言对象及其中的字段。

1 个答案:

答案 0 :(得分:2)

正如您所说,Language属性位于ViewModel类中。但是在DataTemplate中使用它会使它在Employee类中搜索,而不是在ViewModel中搜索。

您需要访问ListBox的DataContext,您可以使用RelativeSource

进行操作
<TextBlock Text="{Binding Path=DataContext.Language.ContactNumber,
      RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ListBox}}"/>

<强>更新

评论:

  

使用此绑定正确解析,但它仍然无法更新   当我改变语言模型时。

首先,例如要在GUI上更新的属性,您需要在ViewModel类上实现INotifyPropertyChanged

但是,这对静态属性不起作用。要在GUI上更新静态属性,必须将它们重新绑定到WPF 4.5。如果您使用的是WPF 4.5,则可以使用StaticPropertyChanged执行此操作。请参阅此处的详细信息WPF 4.5 binding and change notification for static properties

相关问题