2014-10-08 62 views
0

我使用Prism for Windows Runtime来将View中的事件与ViewModels中的DelegateCommands连接起来。我想知道什么是从包含按钮(或自定义控件派生的freom Button类)的ListView调用命令(例如,选择项目)的最佳方式。我想保留Button控件提供的效果(例如背景更改,倾斜效果)。但按钮遗憾的是吸收了点击事件,其中,在后果,我不能在ListView使用挂钩,例如与下面的XAML(和行为SDK)我的命令:在MVVM中调用ListView中的命令

<ListView ItemsSource="{Binding AvailableItemsList}" SelectionMode="Single"> 
    <ListView.ItemTemplate> 
     <DataTemplate> 
      <customControls:NavMenuButton Style="{StaticResource SelectionListMenuButton}" Content="{Binding Nickname}" DescriptionText="{Binding Name}" /> 
     </DataTemplate> 
    </ListView.ItemTemplate> 
    <i:Interaction.Behaviors> 
     <core:EventTriggerBehavior EventName="SelectionChanged"> 
      <core:InvokeCommandAction Command="{Binding ItemSelectedCommand}" /> 
     </core:EventTriggerBehavior> 
    </i:Interaction.Behaviors> 
</ListView> 

什么将是最好的方式做到这一点?我发现了类似的问题,但这里的区别在于列表项中的控件显然是“窃取”了点击事件(尽管它适用于例如简单的TextBlock)。

+0

为什么不绑定的SelectedItem而不是使用eventrtrigger的东西? – blindmeis 2014-10-09 06:05:57

+1

嗡嗡声你想在你的视图模式中从你的按钮在你的视图模式中调用methode?如果是这样,你只需要使用listviewdatacontext并像这样调用你的命令。 Command =“{Binding DataContext.YourCommand,elementName = yourListView} – MatDev8 2014-10-09 09:22:14

+0

@blindmeis:你的意思是SelectionChanged?我的理解是它没有实现ICommand,所以我需要在代码后面添加一些逻辑。真的问题,但以某种方式打破了模式,我误解了吗? – jerry 2014-10-09 12:23:45

回答

1

要关闭这个问题,这里是一个基于MatDev8的评论上面的解决方案(谢谢!):

<ListView x:Name="myListView" ItemsSource="{Binding AvailableItemsList}" SelectionMode="Single"> 
    <ListView.ItemTemplate> 
     <DataTemplate> 
      <customControls:CustomTextButton Style="{StaticResource SelectionListMenuButton}" 
              Content="{Binding Nickname}" 
              DescriptionText="{Binding Name}" 
              Command="{Binding DataContext.ItemSelectedCommand, ElementName=myListView}" 
              CommandParameter="{Binding Name}"/> 
     </DataTemplate> 
    </ListView.ItemTemplate> 
</ListView> 
0

要在ListView中绑定命令,您可以使用ListView中的按钮。

现在为了点击相关的问题,您可以修改您的按钮的Controltemplate,使其看起来像一个简单的文本块。这样你的点击也可以在列表视图上工作,并且不会显示为按钮。

<ControlTemplate TargetType="Button"> 
     <TextBlock Text="{TemplateBinding Content}" /> 
    </ControlTemplate> 

您还可以自定义其他方式click事件如移动焦点到按钮也应该提高自己的点击事件(间接激发你的命令)。这将有助于你的Listview,只要移动到下一个项目也应该触发命令。

+0

谢谢。我想我需要理解,我的控制模板看起来有点像你所建议的 - 稍微复杂一点,它增加了第二行,包含VisualStateManager。简化它可以消除效果,但是按钮仍然会将List事件从ClickView事件中剔除,我可以通过将按钮的IsEnabled属性设置为False来防止这种情况发生,在这种情况下,我也会失去效果,但它然后起作用。 在你的答案的第二部分,你的意思是在后面的代码中调用该命令?我认为,但希望能够直接在XAML中绑定命令。 – jerry 2014-10-09 12:22:54