我的列表框绑定到项目源,selecteditem属性也绑定 . 我的大部分工作都是在选定的房产中完成的 . 实际上我有两个列表框,对于第一个列表框中的每个项目,集合中都有一些子项 . 对于在第一个列表框中选择的所有项目,它们的子项目应该添加在第二个列表框中 .
问题是选择项目(通过选中复选框)不会引发SelectedItem属性更改
我的列表框控件的XAML是
<ListBox SelectionMode="Multiple" ItemsSource="{Binding Charts,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" SelectedItem="{Binding SelectedChart, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox Content="{Binding ChartName}" VerticalAlignment="Center" IsChecked="{Binding IsChartSelected, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<ListBox ItemsSource="{Binding Tracks, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
<ListBox.ItemTemplate>
<DataTemplate >
<StackPanel Orientation="Horizontal">
<CheckBox VerticalAlignment="Center" IsChecked="{Binding IsTrackSelected}"/>
<TextBlock Margin="5 0 0 0" VerticalAlignment="Center" Text="{Binding TrackName}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
视图模型中的我的图表选择更改属性是
public ChartSourceForMultipleSelection SelectedChart
{
get { return _selectedChart; }
set
{
_selectedChart = value;
ChartSelectionChanged();
NotifyPropertyChanged("SelectedChart");
}
}
1 回答
这种绑定没有任何意义:
<CheckBox IsChecked =“{绑定IsTrackSelected,
RelativeSource = {RelativeSource AncestorType = {x:Type ListBoxItem}}}“/>
这会尝试绑定到外部ListBoxItem上的属性IsTrackSelected,但不存在此类属性 . 如果IsTrackSelected是基础数据项的属性,则此处看起来您不需要RelativeSource .
另外,我'm not sure why you'是一个
ListBox
的轨道集合;看起来您的轨道选择概念与所选项目的ListBox
概念是分开的 . 为什么不使用简单的ItemsControl
呢?至于你的主要问题,项目模板中的
CheckBox
正在吃鼠标/焦点事件,这些事件通常会告诉ListBox
在点击时选择父级ListBoxItem
. 只要内部CheckBox
接收到键盘焦点,您就可以手动更新ListBoxItem
的选择状态 .将
GotKeyboardFocus="OnChartCheckBoxGotKeyboardFocus"
添加到CheckBox
您的图表列表项模板,为图表列表框指定一个名称,例如x:Name="ChartsList"
,并在后面的代码中写入处理程序: