MVVM模式下 DataTemplate 中控件的绑定

原文: MVVM模式下 DataTemplate 中控件的绑定

  今天给ListBox中通过DataTemplate生成的Button绑定命令时,一开始Button始终找不到绑定的命令。现找到了正确的绑定方式,特来记录一下。

  先上个正确的示例: 

<ListBox Grid.Column="0" ItemsSource="{Binding CallBussiness}">
    <ListBox.ItemsPanel>
         <ItemsPanelTemplate>
                <WrapPanel HorizontalAlignment="Right" VerticalAlignment="Center" Orientation="Horizontal" />
         </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel>
<TextBlock Text="{Binding Property1}"/> <Button VerticalAlignment="Top" HorizontalAlignment="Left" Margin="25,0,0,0" Command="{Binding Path=DataContext.HandUpCommand, RelativeSource={RelativeSource AncestorType={x:Type ListBox}}}" CommandParameter="{Binding}"/> </StackPanel> </DataTemplate> </ItemsControl.ItemTemplate> </ListBox>

因为使用DataTemplate时,ListBoxItem的DataContext将是ItemsSource绑定的列表的项,其类型就是列表中的单个Model。所以不能使用默认的绑定源,而要使用相对源(RelativeSource)。并且MVVM模式下,VM一般都是绑定窗口到DataContext,窗口中的控件再继承(可能这个词不是很准确)窗口的DataContext,因此指定相对源后,Path还需要从DataContext属性开始找想要的命令。如上面的Button,不能直接Path=HandUpCommand,因为HandUpCommand不是直接存在ListBox中的。

猜你喜欢

转载自www.cnblogs.com/lonelyxmas/p/9091180.html