多个 Listview 中只有一个选定项

6
我有多个ListViews,每个ListViews都与自己的itemsource绑定。但我只有一个选定项。
例如,我有5个ListBoxes(星期一,星期二等),每个ListBox都有自己的itemsource(MondayList,TuesdayList等)。这些ListViews的SelectedItem属性都绑定到属性“CurrentToDo”。
问题是,如果我在星期一选择一个,然后在星期二选择一个,它们都被选中了。
因此,在所有ListViews中只能选择一个项目,请帮忙解决。
<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个回答

11

这里是答案:

绑定时,使用SelectedValue而不是SelectedItem。


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                
        }
    }
}

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接