WPF数据模板中绑定事件不触发问题
今天比较闲,做一个练手的项目,结果在xaml中写了一个用户的数据模板后,在其中的某个Canvas上绑定了一个鼠标左击的事件,结果调试的时候,无论怎么点击都不跳到断点那里,百思不得其解。
之后尝试不绑定事件,直接采用内联事件的写法,将事件写在控件上,并且事件的处理写在cs代码而非ViewModel中,则可以使用,如此可以判断是采用MVVM时,命令没有成功绑定到事件上。
刚开始以为是DevExpress的MVVM框架的BUG。后来改成自己手写的MVVM,并未解决问题,思考再三,觉得是数据模板并未获取到DataContext导致,于是将Canvas绑定的命令做了如下修改,将Canvas的数据上下文明确为最上层父节点的数据上下文,修改后问题解决,经过思考觉得是窗体资源不会被窗体的上下文所修饰,个人见解,并未验证。
修改前:
<Canvas Width="350" Height="80"> <dxmvvm:Interaction.Triggers> <dxmvvm:EventToCommand EventName="MouseLeftButtonDown" Command="{Binding ClickChatWindowToSomeOne}" PassEventArgsToCommand="True"/> </dxmvvm:Interaction.Triggers> <Image Width="60" Height="60" Canvas.Top="30" Canvas.Left="20"> <Image.Source> <MultiBinding Converter="{StaticResource imageconveter}"> <Binding Path="headimg"/> <Binding Path="sex"/> </MultiBinding> </Image.Source> </Image> <Canvas Background="LightPink"> <TextBlock Text="{Binding uname}" Canvas.Left="100" Canvas.Top="40" FontSize="15" Foreground="Black" FontWeight="Bold"> </TextBlock> <TextBlock Text="{Binding describe}" Canvas.Left="100" Canvas.Top="70" FontSize="10" Foreground="Black"/> <StackPanel Orientation="Horizontal" Canvas.Top="40" Canvas.Left="220"> <Image Source="image/location.png" Width="40" Height="40"/> <TextBlock Text="{Binding lastlocal}" FontSize="10" FontWeight="Bold" VerticalAlignment="Center"></TextBlock> </StackPanel> </Canvas> <Separator Margin="0, 5, 0, 5"/> </Canvas>
修改后:{修改后的AncestorType是调用此数据模板的父节点}
<Canvas Width="350" Height="80"> <dxmvvm:Interaction.Triggers> <dxmvvm:EventToCommand EventName="MouseLeftButtonDown" Command="{Binding DataContext.ClickChatWindowToSomeOne,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=ItemsControl}}" PassEventArgsToCommand="True"/> </dxmvvm:Interaction.Triggers> <Image Width="60" Height="60" Canvas.Top="30" Canvas.Left="20"> <Image.Source> <MultiBinding Converter="{StaticResource imageconveter}"> <Binding Path="headimg"/> <Binding Path="sex"/> </MultiBinding> </Image.Source> </Image> <Canvas Background="LightPink"> <TextBlock Text="{Binding uname}" Canvas.Left="100" Canvas.Top="40" FontSize="15" Foreground="Black" FontWeight="Bold"> </TextBlock> <TextBlock Text="{Binding describe}" Canvas.Left="100" Canvas.Top="70" FontSize="10" Foreground="Black"/> <StackPanel Orientation="Horizontal" Canvas.Top="40" Canvas.Left="220"> <Image Source="image/location.png" Width="40" Height="40"/> <TextBlock Text="{Binding lastlocal}" FontSize="10" FontWeight="Bold" VerticalAlignment="Center"></TextBlock> </StackPanel> </Canvas> <Separator Margin="0, 5, 0, 5"/> </Canvas>