musay
musay

Reputation: 88

Edit HyperLink NavigationURI WPF

I'm new to WPF. I have a ComboBox with multiple values and a HyperLink, whenever the ComboBox value changes, I want to change the NavigateUri of the HyperLink accordingly.

In the cs file, I have a dictionary, where the keys are the same as the combo items, and the value of each key is the link I want to navigate to according to the ComboBox selection.

 LinkQuery["A"] = "https://google.com";
 LinkQuery["B"] = "https://facebook.com";
 LinkQuery["C"] = "https://Youtube.com";

<ComboBox x:Name="box_ComboBox"  Visibility="Visible"  Grid.Column="5" Grid.Row="4" Width="90"
    ItemsSource="{Binding Path=Fields}"
    IsSynchronizedWithCurrentItem="True"
    SelectedValue="{Binding Path=Field}" Grid.ColumnSpan="2" HorizontalAlignment="Left" Height="22" VerticalAlignment="Top" SelectionChanged="component_ComboBox_SelectionChanged"/>

....

<TextBlock x:Name="LinkToQuery" Grid.Row="39" Grid.Column="1" Grid.ColumnSpan="4" Margin="10">           
            <Hyperlink x:Name="URLQuery" RequestNavigate="Hyperlink_RequestNavigate" Foreground="Blue">
                Selected: A
            </Hyperlink>
 </TextBlock>

And the cs file:

private void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e)
    {
        Process.Start(e.Uri.AbsoluteUri);
        e.Handled = true;
    }

private void component_ComboBox_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
    {
        string selectedComponent = box_ComboBox.SelectedItem.ToString();
        LinkToQuery.Text = string.Format("Selected: {0} ", box_ComboBox.SelectedItem.ToString());
        URLQuery.NavigateUri = new System.Uri(LinkQuery[selectedComponent],System.UriKind.Absolute);

    }

When I change the Combo selection, the text does change properly, but the link does not work.

Thank you.

Upvotes: 0

Views: 248

Answers (1)

mm8
mm8

Reputation: 169330

Put a Run element inside the Hyperlink and set the Text property of this one:

<TextBlock x:Name="LinkToQuery" Grid.Row="39" Grid.Column="1" Grid.ColumnSpan="4" Margin="10">           
    <Hyperlink x:Name="URLQuery" RequestNavigate="Hyperlink_RequestNavigate" Foreground="Blue">
        <Run x:Name="linkText" Text="Selected: A" />
    </Hyperlink>
</TextBlock>

private void component_ComboBox_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
    string selectedComponent = box_ComboBox.SelectedItem.ToString();
    linkText.Text = string.Format("Selected: {0} ", selectedComponent);
    URLQuery.NavigateUri = new System.Uri(LinkQuery[selectedComponent], System.UriKind.Absolute);
}

Upvotes: 1

Related Questions