开发者

ListBox with hyperlink -> selection changed

开发者 https://www.devze.com 2023-04-09 15:02 出处:网络
I want to do with xaml bindings such feature: Listbox contains hyperlinks. When hyperlink clicked - we go to another frame

I want to do with xaml bindings such feature:

Listbox contains hyperlinks.

When hyperlink clicked - we go to another frame

But also SelectedItem must changed, and on another frame we show info about selected item.

I want it without subscribing click/selected events. Only declarative

Example of my listbox

 <ListBox Grid.Row="1" 
        x:Name="OrderTypesListBox"          
        ItemsSource="{Binding OrderTypes, Mode=OneWay}"
        SelectedItem="{Binding SelectedCall.OrderType, Mode=TwoWay}"            
    >
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel>
                <TextBlock Text="{Binding Name}" />
                    <HyperlinkButton Style="{StaticResource LinkStyle}" NavigateUri="/WindowPage" TargetName="ContentFrame" Content="WindowPage"/>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>      

Now solve like that

<ListBox Grid.Row="1" 
        x:Name="OrderTypesListBox"          
        ItemsSource="{Binding OrderTypes, Mode=OneWay}"
        SelectedItem="{Binding SelectedCall.OrderType, Mode=TwoWay}"            
    >
        <ListBox.ItemTemplate>
            <DataTemplate>
                <HyperlinkButton                            
                    TargetName="ContentFrame" 
                    NavigateUri="{Binding OrderTypeNextPage}"                           
                    Content="{Binding Name}"
                    Click="HyperlinkButton_Click"
                    Tag="{Binding}"
                />
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

private void HyperlinkButton_Click(object sender, RoutedEventArgs e)
  开发者_如何学Go  {
        OrderTypesListBox.SelectedItem = (sender as HyperlinkButton).Tag;
    }


Don't use a HyperlinkButton. Perform the needed actions when the SelectedItem changes in your ViewModel.

Edit: If you need to respond to all click events even if the item is already selected then you can use a Behavior to do this. Just create a behavior for the TextBlock that navigates on the TextBlock click event.

Edit2: Behaviors are pretty simple to code up and easy to use (and don't break the MVVM paradigm).

public class NavigatingTextBlockBehavior : Behavior<TextBlock>
{
  protected override void OnAttached()
  {
    AssociatedObject.MouseLeftButtonDown += new MouseButtonEventHandler(OnMouseDown);
  }

  private void OnMouseDown(object sender, MouseButtonEventArgs e)
  {
      NavigationService.Navigate(new Uri("/WindowPage"));
  }
}
0

精彩评论

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

关注公众号