WPF ListBoxItem DataTemplate Command无效问题

1 篇文章 0 订阅

今天使用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 命令了。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值