syn3rgy syn3rgy - 1 month ago 17
C# Question

Passing and Storing Strings

I'm trying to pass some strings(className & classID) and store them in a different variable(classNameClicked & classIDClicked) based on what hyperlink the user clicked.

Here is my code behind(C#) for creating the hyperlinks:

TextBlock txt = new TextBlock();
txt.TextWrapping = TextWrapping.Wrap;
txt.Foreground = Brushes.Black;
txt.FontFamily = new FontFamily("Times New Roman");
txt.FontSize = 25;
txt.Margin = new Thickness(5);

TextBlock ClassID = new TextBlock();
ClassID.Visibility = Visibility.Collapsed;
ClassID.Text = classID;

Run run = new Run(className);
Hyperlink link = new Hyperlink(run);
link.Click += Link_Click;
txt.Inlines.Add(ClassID);
txt.Inlines.Add(link);

myStackPanel.Children.Add(txt);
frame.Content = myStackPanel;


I was able to pass the string from the className to classNameClicked by extracting the text from the hyperlink using the code below:

private void Link_Click(object sender, RoutedEventArgs e)
{
classNameClicked = ((sender as Hyperlink).Inlines.FirstInline as Run).Text;
classIDClicked = (sender as Textblock).Text;

Class_Page class_page = new Class_Page();
NavigationService.Navigate(class_page);
}


However, I cant seem to figure out how to extract the string from classID.
Please help.

Answer

You just have to reference the parent of your Hyperlink.

So instead of

classNameClicked = ((sender as Hyperlink).Inlines.FirstInline as Run).Text;
classIDClicked = (sender as TextBlock).Text;

you can write

Hyperlink link = sender as Hyperlink;
classNameClicked = (link.Inlines.FirstInline as Run).Text;
classIDClicked = (link.Parent as TextBlock).Inlines.OfType<Run>().First().Text;

If you don't want to use LINQ you could also write:

classIDClicked = ((link.Parent as TextBlock).Inlines.FirstInline as Run).Text;

But I have the same overall opinion as Mat in the comments. This is really ugly and MVVM would be the way to go for writing much cleaner code.

Additionally you should probably add some null checking too.

Edit as requested in the comment:
If you don't want to display the classID in your GUI then you could hide it in the Tag of the Hyperlink:

Hyperlink link = new Hyperlink(run);
link.Tag = classID;
link.Click += Link_Click;

And then just get it in your Click handler:

classIDClicked = link.Tag as string;

You don't need a hidden TextBlock for that.