Sw1a
Sw1a

Reputation: 245

Get an object by click c# Windows 8

Sorry i'm new in C# and i'm looking everywhere, and can't find even it looks easy to do. I want to get the object by click on it but i don't know how to do it.

A simple button in xaml :

<TextBlock 
         Text="{Binding ProjectName}"
         VerticalAlignment="Center" Tapped="On_Tapped_Project"/>

And i Use a simple function :

    private void On_Tapped_Project(object sender, TappedRoutedEventArgs e)
    {
        this.Frame.Navigate(typeof(NoteFolders), MyProjects[3]);
    }

But i would like to have the specific project like MyProjects[x] x=(click Project).

Any ideas ?

Upvotes: 1

Views: 875

Answers (4)

private void On_Tapped_Project(object sender, TappedRoutedEventArgs e)
{
    var projectID = ((TextBlock)sender).Tag as int;
    Frame.Navigate(typeof(NoteFolders), MyProjects[projectID]);
}

is a way to do it, but it is by far more recommended to do it this way:

private void On_Tapped_Project(object sender, TappedRoutedEventArgs e)
{
    var projectID = (sender as TextBlock).Tag as int;
    Frame.Navigate(typeof(NoteFolders), MyProjects[projectID]);
}

"sender as ElementType" is the correct way to cast sender, other methods can cause minor issues, always do the best code and never wonder why it went wrong that one time.

Upvotes: 0

Bablo
Bablo

Reputation: 916

Try this

var element = (sender as FrameworkElement);
  if (element != null)
  {
    var project = element.DataContext as Project;
    if (project != null)
    {
      //Implementation
    }
  }

Upvotes: 3

Viacheslav Smityukh
Viacheslav Smityukh

Reputation: 5843

You can store project id in a tag property of a control

<TextBlock 
    Text="{Binding ProjectName}" Tag="{Binding ProjectID}"
    VerticalAlignment="Center" Tapped="On_Tapped_Project"/>

You can recover it by access to a tag property

private void On_Tapped_Project(object sender, TappedRoutedEventArgs e)
{
    var projectID = ((TextBlock)sender).Tag as int;
    Frame.Navigate(typeof(NoteFolders), MyProjects[projectID]);
}

Upvotes: 0

Jan Hommes
Jan Hommes

Reputation: 5152

You need to cast the event OriginalSource to your type (e.g. Project):

this.Frame.Navigate(typeof(NoteFolders), (Project) e.OriginalSource);

Upvotes: 0

Related Questions