0

我有一个列表视图并将视图用作网格视图,如下所示:

<ListView Grid.Row="1" Grid.Column="0" Height="100" HorizontalAlignment="Left" Margin="10,10,10,10" Name="listView2" VerticalAlignment="Top" Width="300" ItemsSource="{Binding}" SelectionChanged="listView2_SelectionChanged" SelectionMode="Multiple">
            <ListView.View>
                <GridView AllowsColumnReorder="True">

                    <GridViewColumn Header="Select">
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <CheckBox  />
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>
                    </GridViewColumn>

                    <GridViewColumn DisplayMemberBinding="{Binding Path=FirstName}" Header="First Name" Width="100"/>
                    <GridViewColumn DisplayMemberBinding="{Binding Path=LastName}" Header="Last Name" Width="100"/>

                </GridView>
            </ListView.View>    
        </ListView>

现在的问题是,当用户选中复选框时,应该选择记录。同样是用户从列表中选择记录,然后应该选择相应的复选框。

怎么做 ?

4

2 回答 2

3

我假设您的视图模型具有 IsSelected 属性:

    public Boolean IsSelected
    {
        get { return isSelected; }
        set
        {
            if (isSelected != value)
            {
                isSelected = value;
                OnPropertyChanged("IsSelected");
            }
        }
    }
    private Boolean isSelected;

所以,让我们改变标记:

<ListView ItemsSource="{Binding}" SelectionMode="Multiple">
    <!-- add style for the item in list view: -->
    <ListView.ItemContainerStyle>
        <Style TargetType="ListViewItem">
            <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}"/>
        </Style>
    </ListView.ItemContainerStyle>
    <ListView.View>
        <GridView AllowsColumnReorder="True">

            <GridViewColumn Header="Select">
                <GridViewColumn.CellTemplate>
                    <DataTemplate>
                        <!-- bind the checkbox to the IsSelected property: -->
                        <CheckBox IsChecked="{Binding IsSelected, Mode=TwoWay}" />
                    </DataTemplate>
                </GridViewColumn.CellTemplate>
            </GridViewColumn>

            <GridViewColumn DisplayMemberBinding="{Binding Name}" Header="Name" Width="100"/>
        </GridView>
    </ListView.View>
</ListView>
于 2012-05-22T11:06:23.163 回答
2

最简单的方法:

      <GridViewColumn Header="None">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <CheckBox Width="50"
                                      Height="50"
                                      IsChecked="{Binding RelativeSource={RelativeSource AncestorType={x:Type ListViewItem}},
                                                          Path=IsSelected,Mode=TwoWay}" />

                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
于 2012-05-22T12:50:23.073 回答