Silverlight ListBox - 选择状态发生时更改

时间:2011-08-19 15:22:12

标签: silverlight

我有一个用作导航菜单的ListBox。选择项目时,它具有突出显示的状态。如果有未保存的更改,我现在已经在离开页面时实现了一个消息框。问题是,ListBoxItem的可视状态在点击时更改为选中状态。我需要能够将状态更改为从代码中选择,而不是单击。

有没有办法覆盖click事件,以致它不会导致ListBoxItem进入选定状态?然后我可以做VisualStateManager.GoToState(item, "Selected", true)

如果没有,有没有办法为ListBoxItem创建自定义可视状态?

1 个答案:

答案 0 :(得分:1)

您应该从项容器中断MouseLeftButtonDown事件的路由,并从视图模型中设置所选项。例如:

XAML

<ListBox x:Name="lb">
   <ListBoxItem>
      <TextBlock MouseLeftButtonDown="TextBlock_OnMouseLeftButtonDown" Text="Test"/>
   </ListBoxItem>
 </ListBox>

事件处理程序

 private void TextBlock_OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
 {
      //interrups item selection
      e.Handled = true;
      //here you can show "Do you want navigate from?" dialog
      // and if user accepts then show selected item in menu using SelectedItem or SelectedIndex
      lb.SelectedIndex = 0;
 }
相关问题