1

对不起,我是 C# 的新手,我到处找,即使看起来很容易也找不到。我想通过单击来获取对象,但我不知道该怎么做。

xaml 中的一个简单按钮:

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

我使用一个简单的功能:

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

但我想有具体的项目,如MyProjects[x] x=(click Project).

有任何想法吗 ?

4

4 回答 4

3

试试这个

var element = (sender as FrameworkElement);
  if (element != null)
  {
    var project = element.DataContext as Project;
    if (project != null)
    {
      //Implementation
    }
  }
于 2013-01-30T10:49:06.827 回答
0

您需要将事件 OriginalSource 转换为您的类型(例如项目):

this.Frame.Navigate(typeof(NoteFolders), (Project) e.OriginalSource);
于 2013-01-30T10:48:39.503 回答
0

您可以将项目 ID 存储在控件的标记属性中

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

您可以通过访问标签属性来恢复它

private void On_Tapped_Project(object sender, TappedRoutedEventArgs e)
{
    var projectID = ((TextBlock)sender).Tag as int;
    Frame.Navigate(typeof(NoteFolders), MyProjects[projectID]);
}
于 2013-01-30T10:48:48.360 回答
0
private void On_Tapped_Project(object sender, TappedRoutedEventArgs e)
{
    var projectID = ((TextBlock)sender).Tag as int;
    Frame.Navigate(typeof(NoteFolders), MyProjects[projectID]);
}

是一种方法,但更推荐这样做:

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”是正确的方法来转换发件人,其他方法可能会导致小问题,总是做最好的代码,永远不要想为什么会出错。

于 2014-04-28T17:59:57.023 回答