Windows Phone 7-无法从ViewModel触发事件
本文关键字:ViewModel 事件 Phone Windows | 更新日期: 2023-09-27 18:00:40
我想从视图模型中为列表框编写事件。我试着这样做:-
<ListBox.ItemTemplate>
<DataTemplate>
<Border BorderBrush="Gray" Padding="5" BorderThickness="1">
<StackPanel Orientation="Horizontal">
<Border BorderBrush="Wheat" BorderThickness="1">
<Image Name="ListPersonImage" Source="{Binding PersonImage}" Height="100" Width="100" Stretch="Uniform" Margin="10,0,0,0"/>
</Border>
<TextBlock Text="{Binding FirstName}" Name="firstName" Width="200" Foreground="White" Margin="10,10,0,0" FontWeight="SemiBold" FontSize="22" />
<Button DataContext="{Binding DataContext, ElementName=listBox1}" Command="{Binding addPerson}" Height="80" Width="80" >
<Button.Background>
<ImageBrush ImageSource="{Binding imagePath, Converter={StaticResource pathToImageConverter}}" Stretch="Fill" />
</Button.Background>
</Button>
</StackPanel>
</Border>
<i:Interaction.Triggers>
<i:EventTrigger EventName="Tap">
<i:InvokeCommandAction Command="{Binding ItemSelectedCommand,Mode=OneWay}" CommandParameter="{Binding}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
我的视图模型:-
public RelayCommand<MVVMListBoxModel> ItemSelectedCommand { get; private set; }
public MVVMListBoxViewModel()
{
ItemSelectedCommand = new RelayCommand<MVVMListBoxModel>(ItemSelected);
}
private void ItemSelected(MVVMListBoxModel myItem)
{
MessageBox.Show("Name==>" + myItem.FirstName);
//throw new NotImplementedException();
}
但什么也没发生。请告诉我我错在哪里。提前谢谢。
检查输出窗口以查看是否出现绑定错误。看起来你得到了一个,因为你在MVVMListBoxViewModel
中定义了ItemSelectedCommand
,但ListBoxItem
的DataContext
是对应的MVVMListBoxModel
,所以绑定引擎找不到命令。
尝试将ItemSelectedCommand
的定义移动到MVVMListBoxModel
,并查看消息框是否以这种方式显示。
是否希望触发器位于Listbox
项的SelectionChanged
上?那么触发器应该在<ListBox.ItemTemplate> ... </ListBox.ItemTemplate>
之外。
触发器应将CommandParamter
绑定到SelectedItem
<i:Interaction.Triggers>
<i:EventTrigger EventName="Tap">
<i:InvokeCommandAction Command="{Binding ItemSelectedCommand,Mode=OneWay}" CommandParameter="{Binding SelectedItem}"/>
</i:EventTrigger>
</i:Interaction.Triggers>