今天使用wpf的prism开发项目时,需要有在ListBox中的ListBoxItem触发命令的需求,
在创建ListBoxItem的DataTemplate时,将prism的viewmodel中定义的command绑定到DataTemplate的Command上,
如下:
<DataTemplate x:Key="CanIdTemplate" DataType="{x:Type sys:String}">
<materialDesign:Chip Content="{Binding}" Margin="5,5,0,0" IsDeletable="True"
DeleteCommand="{Binding CanIdChipDeleteCommand}">
</materialDesign:Chip>
</DataTemplate>
但在运行时发现 CanIdChipDeleteCommand
没有触发。
然后将 materialDesign:Chip
单独放到其他控件容器里运行时可以正确触发命令。
经试验分析,应该是因为 DataTemplate 与 数据模板运行时加载所在的控件 的上下文是独立的,
而默认绑定情况下在prism的ViewModel中定义的CanIdChipDeleteCommand
命令在 DataTemplate 中的上下文找不到。
可以通过修改绑定方式,将命令绑定的目标关联到与 ViewModel 所在的同一个上下文中。
修改代码如下:
<UserControl x:Class="VrmsServer.Desktop.Views.Functions.Configure.TboxCanIdSettingControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:prism="http://prismlibrary.com/"
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:converter="clr-namespace:VrmsServer.Desktop.Converter"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
Background="#d7d7d7" x:Name="userControl"
prism:ViewModelLocator.AutoWireViewModel="True">
<UserControl.Resources>
<DataTemplate x:Key="CanIdTemplate" DataType="{x:Type sys:String}">
<materialDesign:Chip Content="{Binding}" Margin="5,5,0,0"
IsDeletable="True"
DeleteCommand="{Binding ElementName=userControl, Path=DataContext.CanIdChipDeleteCommand}"
DeleteCommandParameter="{Binding}">
</materialDesign:Chip>
</DataTemplate>
</UserControl.Resources>
</UserControl>
代码修改如上后,可以正确触发 ViewModel
中的 CanIdChipDeleteCommand
命令了。