0

This is my XAML markup:

<TextBlock>
    <Hyperlink Click="InstrumentFile_Click">
        <Run Text="{Binding InstrumentFile}"/>
    </Hyperlink>
</TextBlock>

C#:

private void InstrumentFile_Click(object sender, RoutedEventArgs e)
{
    Hyperlink link = sender as Hyperlink;
    if (link != null)
    {
        //need to get text here
    }
}

I want to get the text that is bound to Run. How can I get? Thanks!

Jack
  • 7,433
  • 22
  • 63
  • 107

1 Answers1

3

It's a silly situation. You've written a class with a InstrumentFile member, and bound to it by the view. Now you want to programmatically access the view in order to get the data you gave it in the first place? It's backwards!

Just access the InstrumentFile member directly. You wrote the code in the first place!

Kieren Johnstone
  • 41,277
  • 16
  • 94
  • 144
  • Not as silly as you think. I haven't implemented MVVM pattern nor am I using INotifyPropertyChanged. The textblock posted here is inside a DataGrid. Could you please clarify how would I know which hyperlink is clicked and access it's text? – Jack Apr 05 '13 at 13:20
  • 1
    The `sender` property gives you the clicked object, and you know that the `DataContext` of it will be the object it's bound to. If you really don't want to use MVVM, get the Hyperlink from `sender`, get the object it's bound to, and access the property. But it's a terrible model which MVVM solves with extreme simplicity and ease – Kieren Johnstone Apr 05 '13 at 13:35
  • That's not what I meant - that comment's code will break with a runtime error if you change the view and forget the code. Just use the object to get the DataContext and grab the class it's bound to. Less likely to change. It's a quality issue here caused by lack of a good code structure.. – Kieren Johnstone Apr 08 '13 at 06:17