积极答复者
自定义 listboxitem 的选中问题

问题
-
<ListBox Name="listBox2" SelectionChanged="listBox2_SelectionChanged" ItemsSource="{Binding}" ><ListBox.ItemTemplate><DataTemplate><StackPanel Orientation="Horizontal" Width="139" KeyDown="CheckBox_KeyDown" ><CheckBox Content="{Binding Path=NAME}" Width="60" IsChecked="True"/><Slider Height="23" Name="slider1" Width="50" Value="10" ValueChanged="slider1_ValueChanged" /></StackPanel></DataTemplate></ListBox.ItemTemplate></ListBox>现在直接点其中1个listboxitem 的CheckBox 和Slide,listboxitem 不能选中。要实现,即使点击CheckBox 和Slider 也能选中这个listboxitem 。
答案
-
分别可以用两种方式:
1。对于CheckBox这种有IsChecked属性的,可以用绑定绑到 ItemContainer 上
IsChecked="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBoxItem}}, Path=IsSelected}"
2。对于Slider,可以处理他的 PreviewMouseDown 事件,找到 ItemContainer 设置他的IsSelected属性:
<Slider Height="23" Name="slider1" Width="50" Value="10" PreviewMouseDown="slider1_MouseDown"/>
C#:
private void slider1_MouseDown(object sender, MouseButtonEventArgs e) { ListBoxItem itemcontainer= listBox2.ItemContainerGenerator.ContainerFromItem((sender as Slider).DataContext as Item) as ListBoxItem; itemcontainer.IsSelected = true; }
Sincerely,
Bob Bao [MSFT]
MSDN Community Support | Feedback to us
Get or Request Code Sample from Microsoft
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
- 已标记为答案 黑心 2011年6月24日 8:08
全部回复
-
分别可以用两种方式:
1。对于CheckBox这种有IsChecked属性的,可以用绑定绑到 ItemContainer 上
IsChecked="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBoxItem}}, Path=IsSelected}"
2。对于Slider,可以处理他的 PreviewMouseDown 事件,找到 ItemContainer 设置他的IsSelected属性:
<Slider Height="23" Name="slider1" Width="50" Value="10" PreviewMouseDown="slider1_MouseDown"/>
C#:
private void slider1_MouseDown(object sender, MouseButtonEventArgs e) { ListBoxItem itemcontainer= listBox2.ItemContainerGenerator.ContainerFromItem((sender as Slider).DataContext as Item) as ListBoxItem; itemcontainer.IsSelected = true; }
Sincerely,
Bob Bao [MSFT]
MSDN Community Support | Feedback to us
Get or Request Code Sample from Microsoft
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
- 已标记为答案 黑心 2011年6月24日 8:08