2014-10-08 58 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