将数据绑定列表框更改为longlistselector

时间:2013-09-30 22:30:28

标签: c# windows-phone-7 longlistselector

我有一个列表框,哪些项目可以打开&通过以下代码查看...

    private void AccountsList_Tap(object sender, System.Windows.Input.GestureEventArgs e)
    {
            var listBoxItem = AccountsList.ItemContainerGenerator.ContainerFromIndex(AccountsList.SelectedIndex) as ListBoxItem;
            var txtBlk = FindVisualChildByType<TextBlock>(listBoxItem, "txtBlkAccountName");
            xCa = txtBlk.Text;

            NavigationService.Navigate(new Uri(string.Format("/ViewAccount.xaml?parameter={0}&action={1}", a.ToString(), "View"), UriKind.Relative));
    }

&安培;

    T FindVisualChildByType<T>(DependencyObject element, String name) where T : class
    {
        if (element is T && (element as FrameworkElement).Name == name)
        {
            return element as T;
        }

        int childcount = VisualTreeHelper.GetChildrenCount(element);

        for (int i = 0; i < childcount; i++)
        {
            T childElement = FindVisualChildByType<T>(VisualTreeHelper.GetChild(element, i), name);
            if (childElement != null)
            {
                return childElement;
            }
        }
        return null;
    }

现在我正在实现longlistselector而不是listbox。 长列表选择器显示我在数据库中的所有项目,但是我在从此列表中打开项目时遇到问题...我无法在此longlistselector中使用SelectedIndex请帮助...

2 个答案:

答案 0 :(得分:1)

要点击项目,请将Tap甚至放在ItemTemplate而不是List中,然后您可以使用sender属性检索所需的值。
而不是使用FindVisualChildByType来获取您想要的值,您应该能够使用DataContext来检索您想要的任何内容:

private void AccountsItem_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
        FrameworkElement element=sender as FrameworkElement ;
        Account item= element.DataContext as Account ;

        xCa = item.Name;

        NavigationService.Navigate(new Uri(string.Format("/ViewAccount.xaml?parameter={0}&action={1}", a.ToString(), "View"), UriKind.Relative));
}

答案 1 :(得分:1)

我建议你改变你的工作流程。而不是收听Tap事件,而是收听SelectionChanged事件。从此事件中,您可以获取SelectedItem。 SelectItem是Items绑定的对象。

示例:您的ItemsSource是List ListBox中的每个项目或LongListSelector绑定到MyObject的一个实例。你的“txtBlkAccountName”TextBlock应该将它的Text绑定到MyObject类的AccountNumber属性。

private void LongListSelector_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
    var myObj = AccountsList.SelectedItem as MyObject;
    if(myObj == null) return;

    var accountNum = myObj.AccountNumber;
    NavigationService.Navigate(new Uri(string.Format("/ViewAccount.xaml?parameter={0}&action={1}", accountNum, "View"), UriKind.Relative));

    // set the selectedItem to null so the page can be navigated to again 
    // If the user taps the same item
    AccountsList.SelectedItem = null;
}
相关问题