MVVM按钮事件,列表视图未获取所选项目

时间:2012-06-14 09:53:04

标签: .net wpf mvvm mvvm-light mvvm-toolkit

我正在尝试从列表视图中获取selectedItem。我在按钮上使用MVVM light toolkit和EventToCommand。

我的listView绑定到正确绑定的ObservableCollection。这是listView xaml:

  <ListView   Name="serverListView"
                    Grid.Row="3"
                    Grid.Column="0"
                    Grid.ColumnSpan="2"
                    ItemsSource="{Binding Servers}"
                    ItemTemplate="{StaticResource ServerList}"
                    SelectionMode="Single"
                    BorderThickness="0"/>

然后我有一个按钮,我正在使用带有mvvm EventToCommand的Interaction.Triggers,我不确定selectedItem绑定是否正确。该事件通过中继命令(mvvm light toolkit)正确触发,但每次都是null。

这是我的按钮xaml;

<Button x:Name="LoadButton"
                Content="Load Server"
                Grid.Column="0"
                Grid.Row="4"
                Grid.ColumnSpan="2">
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="Click">
                    <mvvm:EventToCommand  Command="{Binding ButtonClick, Mode=OneWay}"
                                            CommandParameter="{Binding SelectedItem, ElementName=serverListView}"
                                            MustToggleIsEnabledValue="True"/>
                </i:EventTrigger>
            </i:Interaction.Triggers>
        </Button>

接力命令:

 this.ButtonClick = new RelayCommand<object>(new Action<object>(this.GetClickEvent));

2 个答案:

答案 0 :(得分:1)

摆脱命令参数绑定,在viewmodel中创建一个SelectedServer属性,在没有参数的viewmodel中创建Command

<ListView   Name="serverListView"
                Grid.Row="3"
                Grid.Column="0"
                Grid.ColumnSpan="2"
                ItemsSource="{Binding Servers}"
                ItemTemplate="{StaticResource ServerList}"
                SelectedItem="{Binding SelectedServer}"
                SelectionMode="Single"
                BorderThickness="0"/>

<Button Command="{Binding MyCommand}" />

在您的viewmodel中,您拥有执行命令逻辑所需的所有信息。

答案 1 :(得分:0)

您还应该将listview的SelectedItem属性绑定到viewmodel的属性(SelectedServer),并更改EventToCommand

CommandParameter="{Binding SelectedItem, ElementName=serverListView}"

CommandParameter="{Binding SelectedServer}"
相关问题