[英]WPF ListBox selected item not changed while using DataTemplate
我的列表框已绑定到项目源,并且selecteditem属性也已绑定。 我的大部分工作都是在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");
}
}
这种绑定没有任何意义:
<CheckBox IsChecked="{Binding IsTrackSelected, RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}}}" />
这将尝试绑定到外部
ListBoxItem
上的属性
IsTrackSelected
,但是不存在这样的属性。
如果
IsTrackSelected
是基础数据项的属性,则这里看起来好像不需要
RelativeSource
。
另外,我不确定为什么您是tracks集合的ListBox
; 看起来您的曲目选择概念与所选项目的ListBox
概念是分开的。 为什么不使用简单的ItemsControl
呢?
关于您的主要问题,项目模板中的CheckBox
正在吞噬鼠标/焦点事件,这些事件通常会告诉ListBox
在单击时选择父ListBoxItem
。 每当ListBoxItem
的内部CheckBox
获得键盘焦点时,就可以手动更新其状态。
将GotKeyboardFocus="OnChartCheckBoxGotKeyboardFocus"
添加到CheckBox
您的图表列表项模板,为图表列表框命名,例如x:Name="ChartsList"
,并在后面的代码中编写处理程序:
private void OnChartCheckBoxGotKeyboardFocus(
object sender,
KeyboardFocusChangedEventArgs e)
{
var checkBox = sender as CheckBox;
if (checkBox == null)
return;
var listBoxItem = ItemsControl.ContainerFromElement(ChartsList, checkBox)
as ListBoxItem;
if (listBoxItem != null)
listBoxItem.IsSelected = true;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.