原文:
【WPF】CommandParameter解决多传参问题
方法一:传参按钮控件自身绑定的ItemSource
用WAF框架实现MVVM,按钮的点击事件都要通过Command来传递到这个View对应的ViewModel上,再通过ViewModel传递到上层的Controller层,在Controller层通过DelegateCommand处理按钮真正的事件。有时候需要给该Command附加上一些参数(CommandParameter),但是默认CommandParameter只能传递一个参数。谷歌搜到的解决方法很复杂,于是想了个办法CommandParameter参数传递的是这个按钮控件自身绑定的ItemSource,然后通过从ItemSource身上的DataContext来拿到数据,再截取字符串分割得到想要的部分数据(或者强转为ItemSource对应的实体类)。
正常情况下,Button的绑定:
<Button Command="{Binding BtnCommand}" />
这个Command会沿着View –> ViewModle –> Controller层传递。
如果这个Button是ListBox的Item,这个ListBox的Item要使用数据模板,且ItemsSource绑定到了这组Button的数据源,是这样绑:
<ListBox x:Name="listBox" ItemsSource="{Binding DataList}" ScrollViewer.HorizontalScrollBarVisibility="Disabled">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid x:Name="grid">
<local:WaitingProgress/>
<Button Command="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=DataContext.BtnCommand}"
CommandParameter="{Binding RelativeSource={x:Static RelativeSource.Self}}"> <!-- 传参是Button控件绑定的ItemsSource,即这里是DataList列表 -->
<Image Tag="{Binding id}" x:Name="img" Stretch="UniformToFill" Width="150" Height="150"