WPF ListBoxItem DataTempldate command 执行问题
2013-11-17 23:53
381 查看
今天用到MVVM,在listboxItem中做command处理。因为是要获取数据,修改ListBox模板,但是发现command无法正确执行,写在Item中可以正确执行。
网上也遇到类似问题,但是没有对应的解决办法。最后由@WaitingEver 给予解决。
主要用到RelativeSource,RelativeSource属性可以根据相对于目标的关系指向源对象。通常用于目标对象和源对象不在同一个标记块中,当创建控件模板和数据模板会出现这种情况。用到RelativeSource访问顶级ListBox控件去读取相应的属性。
出错代码:
修正后代码:
网上也遇到类似问题,但是没有对应的解决办法。最后由@WaitingEver 给予解决。
主要用到RelativeSource,RelativeSource属性可以根据相对于目标的关系指向源对象。通常用于目标对象和源对象不在同一个标记块中,当创建控件模板和数据模板会出现这种情况。用到RelativeSource访问顶级ListBox控件去读取相应的属性。
出错代码:
<ListBox.ItemTemplate> <DataTemplate> <Image Margin="5" Source="{Binding}" Width="140" Height="90" Stretch="Fill"> <i:Interaction.Triggers> <i:EventTrigger EventName="MouseEnter"> <i:InvokeCommandAction Command="{Binding ChangeBackGround}" CommandParameter="" /> </i:EventTrigger> </i:Interaction.Triggers> </Image> </DataTemplate> </ListBox.ItemTemplate>
修正后代码:
<ListBox.ItemTemplate> <DataTemplate> <Image Margin="5" Source="{Binding}" Width="140" Height="90" Stretch="Fill"> <i:Interaction.Triggers> <i:EventTrigger EventName="MouseEnter"> <i:InvokeCommandAction Command="{Binding Path=DataContext.ChangeBackGround,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=ListBox}}" CommandParameter="" /> </i:EventTrigger> </i:Interaction.Triggers> </Image> </DataTemplate> </ListBox.ItemTemplate>
相关文章推荐
- WPF ListViewItem ControlTemplate command 不执行问题
- 【WPF】ListBox使用DataTemplate 以及默认选中第一项Item
- WPF开发中遇到的问题及解决系列(二):如何获取通过binding生成的ComboBox或者ListBox等的Item
- 关于WInform中listbox鼠标拖动上下排序item的问题解决
- WPF:在异步操作中使用CommandManager手动更新Command执行状态(转载)
- 基于wpf的相关设计问题-Command的使用
- android gridview的item放大问题,setOnItemSelectedListener不执行的解决办法。
- [问题]mac执行adb命令出现adb: command not found解决方法
- BaseAdapter之getItem不执行问题
- WPF(WP7、WP8)多个Listbox嵌套时滚动问题的解决
- angular 使用data-bs-datepicker时的一个小问题及解决
- SqlCommand.ExecuteNonQuery()执行查询返回值的问题
- ControlTemplate,ItemsPanelTemplate,DataTemplate(wpf)
- 关于WInform中listbox鼠标拖动上下排序item的问题解决
- MySQL一次执行多条语句的实现及常见问题(C API Commands out of sync; you can't run this command now)
- 基于wpf的相关设计问题-Command的使用
- 解决执行脚本时爆“sqlplus: command not found”的问题 推荐
- iOS开发UITableView篇:[self.tableView reloadData]执行时间过长问题解决历程
- WPF关于改变ListBoxItem的颜色的注意事项以及如何找到ListBox中的ItemsPanel
- 关于Listbox的 SelectionChanged 事件 (同一个Item只触发一次问题)