MVVM模式下 DataTemplate 中控件的绑定
生活随笔
收集整理的這篇文章主要介紹了
MVVM模式下 DataTemplate 中控件的绑定
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
今天給ListBox中通過(guò)DataTemplate生成的Button綁定命令時(shí),一開(kāi)始Button始終找不到綁定的命令。現(xiàn)找到了正確的綁定方式,特來(lái)記錄一下。
先上個(gè)正確的示例:
<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>
因?yàn)槭褂肈ataTemplate時(shí),ListBoxItem的DataContext將是ItemsSource綁定的列表的項(xiàng),其類型就是列表中的單個(gè)Model。所以不能使用默認(rèn)的綁定源,而要使用相對(duì)源(RelativeSource)。并且MVVM模式下,VM一般都是綁定窗口到DataContext,窗口中的控件再繼承(可能這個(gè)詞不是很準(zhǔn)確)窗口的DataContext,因此指定相對(duì)源后,Path還需要從DataContext屬性開(kāi)始找想要的命令。如上面的Button,不能直接Path=HandUpCommand,因?yàn)镠andUpCommand不是直接存在ListBox中的。
轉(zhuǎn)載于:https://www.cnblogs.com/MXJ-Blogs/p/7716672.html
與50位技術(shù)專家面對(duì)面20年技術(shù)見(jiàn)證,附贈(zèng)技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的MVVM模式下 DataTemplate 中控件的绑定的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 搭建一个简易的https
- 下一篇: HTTP相关知识