首页 > 其他 > 详细

MVVM模式下 DataTemplate 中控件的绑定

时间:2018-05-26 01:01:53      阅读:261      评论:0      收藏:0      [点我收藏+]
原文: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中的。

MVVM模式下 DataTemplate 中控件的绑定

原文:https://www.cnblogs.com/lonelyxmas/p/9091180.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!