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;
}
精彩评论