开发者

Silverlight ListBox - Change When Selected State Occurs

开发者 https://www.devze.com 2023-03-29 21:28 出处:网络
I have a ListBox that is used as a navigation menu. When an item is selected, it has a state that is highlighted. I have now implemented a message box when navigating away from a page if there are uns

I have a ListBox that is used as a navigation menu. When an item is selected, it has a state that is highlighted. I have now implemented a message box when navigating away from a page if there are unsaved changes. The problem is, the visual state of the ListBoxItem is changed to selected upon click. I need to be able to chan开发者_Go百科ge set the state to selected from code, instead of on click.

Is there a way to override the click event so that it doesn't cause the ListBoxItem to go to the selected state? I could then do VisualStateManager.GoToState(item, "Selected", true).

If not, is there a way to create a custom visual state for the ListBoxItem?


You should interrupt routing of MouseLeftButtonDown event from your item container and set selected item from view model. For instance:

XAML

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

Event Handler

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

精彩评论

暂无评论...
验证码 换一张
取 消