多个Listviews只有一个SelectedItem

时间:2013-12-17 14:11:38

标签: c# .net wpf xaml listview

我有多个Listviews,每个Listviews都绑定了自己的itemsource。但我只有1个选定项目。

例如,我有5个列表框(Monday, Tuesday, ...),每个列表框都有自己的itemssource (MondayList, TuesdayList, ...)。这些Listviews SelectedItem属性中的每一个都绑定到属性'CurrentToDo'。

问题在于,如果我在星期一选择一个,然后在星期二选择一个,则它们都被选中。

因此,在所有列表视图中只能选择一个项目,请帮助。

<UserControl.Resources>        
    <Style x:Key="ListViewItemStyleToDo" TargetType="{x:Type ListViewItem}">
        <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}"/>
    </Style>

    <GridView x:Key="ViewBase1" x:Shared="False" >
        <GridViewColumn Header="" Width="30">
            <GridViewColumn.CellTemplate>
                <DataTemplate>
                    <CheckBox IsChecked="{Binding IsSelected, Mode=TwoWay, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListViewItem}}}" />
                </DataTemplate>
            </GridViewColumn.CellTemplate>
        </GridViewColumn>
        <GridViewColumn Header="Subject" Width="auto" DisplayMemberBinding="{Binding Subject}" />
    </GridView>
</UserControl.Resources>

<ListView Grid.Row="1"  ItemsSource="{Binding MondayList}" SelectedItem="{Binding CurrentToDo, Mode=TwoWay}" SelectionMode="Single" ItemContainerStyle="{DynamicResource ListViewItemStyleToDo}" View="{DynamicResource ViewBase1}" />

<ListView Grid.Row="3"  ItemsSource="{Binding TuesdayList}" SelectedItem="{Binding CurrentToDo,Mode=TwoWay}" SelectionMode="Single" ItemContainerStyle="{DynamicResource ListViewItemStyleToDo}" View="{DynamicResource ViewBase1}"  />

属性:

    private ToDoMod _currentToDo;

    public ToDoMod CurrentToDo
    {
        get { return _currentToDo; }
        set
        {
            _currentToDo= value;
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs("CurrentToDo"));
        }
    }

2 个答案:

答案 0 :(得分:5)

以下是答案:

只需绑定到SelectedValue而不是SelectedItem。

答案 1 :(得分:0)

您需要再添加5个属性:MondayCurrentToDoTuesdayCurrentToDo ...

将每个列表视图的SelectedItem绑定到相应的属性。

在每个属性的setter中,更新CurrentToDo并删除其他列表的选择 - 所以它将如下所示:

private ToDoMod _mondayCurrentToDo;

public ToDoMod MondayCurrentToDo
{
    get { return _mondayCurrentToDo; }
    set
    {
        _mondayCurrentToDo= value;
        CurrentToDo = _mondayCurrentToDo;
        _tuesdayCurrentToDo = null;
        //TODO: add null setters for all other _<dayOfWeek>CurrentToDo members


        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs("MondayCurrentToDo"));
            PropertyChanged(this, new PropertyChangedEventArgs("TuesdayCurrentToDo"));
            //TODO: add notificaitons for all other <DayOfWeek>CurrentToDo properties                
        }
    }
}

当然,将其重构为方法等......