将绑定到itemsource的控件里面的元素绑定到itemsource数据源之外的viewmodel中的数据

发布时间 2023-12-11 12:59:06作者: WangKun666
1 <ComboBox.ItemTemplate>
2     <DataTemplate>
3         <StackPanel Orientation="Horizontal">
4             <TextBlock Width="100" Text="{Binding Key}" />
5 <Button Content="X" Command="{Binding DataContext.DeleteSoundCommand,RelativeSource={RelativeSource AncestorType=UserControl}}" /> 6 </StackPanel> 7 </DataTemplate> 8 </ComboBox.ItemTemplate>

 

 

 

//WPF中提供了InvokeCommandAction可直接在前端xaml文件中触发Viewmodel中的事//件,但该方法存在一个缺陷,只能通过CommandParameter传递参数,而且不能传递鼠标事件arg参数。

InvokeCommandAction的使用方法如下:

首先引入:

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"

 

<Button>

    <i:Interaction.Triggers>

        <i:EventTrigger EventName="MouseEnter" >

            <i:InvokeCommandAction Command="{Binding FooCommand}" CommandParameter=abc/>

        </i:EventTrigger>

    </i:Interaction.Triggers>

</Button>

 

使用Mvvmlight中的EventToCommand, 可解决上述问题。Mvvmlight对System.Windows.Interactivity.dll的某些方面进行了扩展,能够传递事件参数,需要引用GalaSoft.MvvmLight.Extras.dll,实现如下:

xmlns:cmd="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras"

 

<Button>

    <i:Interaction.Triggers>

        <i:EventTrigger EventName="MouseEnter" >

             <cmd:EventToCommand Command="{Binding FooCommand}"

                 PassEventArgsToCommand="True" />

        </i:EventTrigger>

    </i:Interaction.Triggers>

</Button>