[英]Windows Phone 7 - Can not trigger the event from ViewModel.
I want to write the event for list box from View Model. 我想从视图模型中为列表框编写事件。 I try like this:- 我这样尝试:-
<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>
My ViewModel:- 我的ViewModel:-
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();
}
But nothing happening. 但是什么也没发生。 Please let me know where I did mistake. 请让我知道我在哪里做错了。 Thanks in advance. 提前致谢。
Check output window to see if you got binding error. 检查输出窗口以查看是否出现绑定错误。 It seems that you got one, because you have ItemSelectedCommand
defined in MVVMListBoxViewModel
but ListBoxItem
's DataContext
is corresponding MVVMListBoxModel
, so binding engine couldn't find the command. 看来您有一个,因为您在ItemSelectedCommand
定义了MVVMListBoxViewModel
但是ListBoxItem
的DataContext
是对应的MVVMListBoxModel
,因此绑定引擎找不到该命令。
Try to move definition of ItemSelectedCommand
to MVVMListBoxModel
and see if message box get displayed this way. 尝试将ItemSelectedCommand
定义ItemSelectedCommand
MVVMListBoxModel
然后查看消息框是否以这种方式显示。
Do you want the trigger to be upon the SelectionChanged
of the Listbox
Item? 您是否希望触发器基于Listbox
项的SelectionChanged
? Then the trigger should be outside the <ListBox.ItemTemplate> ... </ListBox.ItemTemplate>
. 然后,触发器应该在<ListBox.ItemTemplate> ... </ListBox.ItemTemplate>
。
And the trigger should bind the CommandParamter
to the SelectedItem
并且触发器应将CommandParamter
绑定到SelectedItem
<i:Interaction.Triggers>
<i:EventTrigger EventName="Tap">
<i:InvokeCommandAction Command="{Binding ItemSelectedCommand,Mode=OneWay}" CommandParameter="{Binding SelectedItem}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.