如何使用DataTemplate访问列表框中的特定项目?

时间:2011-03-03 13:05:19

标签: c# xaml windows-phone-7 silverlight-4.0

我有一个ListBox,包括一个带有2个StackPanels的ItemTemplate。 我想要访问的第二个StackPanel中有一个TextBox。 (将其可见性更改为true并接受用户输入) 触发器应该是SelectionChangedEvent。因此,如果用户单击ListBoxItem,TextBlock将变为不可见,TextBox将变为可见。

XAML代码:

<ListBox Grid.Row="1" Name="ContactListBox" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" ItemsSource="{Binding Contacts}" Margin="0,36,0,0" SelectionChanged="ContactListBox_SelectionChanged">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal" Margin="0,0,0,0">
                        <toolkit:ContextMenuService.ContextMenu>
                            <toolkit:ContextMenu>
                                <toolkit:MenuItem Header="Edit Contact" Click="ContactMenuItem_Click"/>
                                <toolkit:MenuItem Header="Delete Contact" Click="ContactMenuItem_Click"/>
                            </toolkit:ContextMenu>
                        </toolkit:ContextMenuService.ContextMenu>

                        <Grid>
                            <Rectangle Fill="{StaticResource PhoneAccentBrush}"
                                           Width="72" Height="72">
                                <Rectangle.OpacityMask>
                                    <ImageBrush ImageSource="/Images/defaultContactImage.png" Stretch="UniformToFill"/>
                                </Rectangle.OpacityMask>
                            </Rectangle>
                        </Grid>
                        <StackPanel>
                            <TextBox Text="{Binding Name}" TextWrapping="Wrap" Visibility="Collapsed"/>
                            <TextBlock Text="{Binding Name}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}" />
                            <TextBlock Text="{Binding Number}" TextWrapping="Wrap" Margin="12,-6,12,0" Style="{StaticResource PhoneTextAccentStyle}"/>
                        </StackPanel>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

我想有几种方法可以解决这个问题,但我没有尝试过。

我目前的做法是这样的

    private void ContactListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        ListBoxItem listBoxItem = ContactListBox.SelectedItem as ListBoxItem;

        DataTemplate listBoxTemplate = listBoxItem.ContentTemplate;

        // How to access the DataTemplate content?

        StackPanel outerStackPanel = listBoxTemplate.XXX as StackPanel;

        StackPanel innerStackPanel = outerStackPanel.Children[1] as StackPanel;

        TextBox nameBox = innerStackPanel.Children[0] as TextBox;
        TextBlock nameBlock = innerStackPanel.Children[1] as TextBlock;


        nameBox.Visibility = System.Windows.Visibility.Visible;
        nameBlock.Visibility = System.Windows.Visibility.Collapsed;

    }

5 个答案:

答案 0 :(得分:28)

谢谢你的帮助!终于我明白了。解决了VisualTreeHelper的问题。多么棒的功能^^

private void ContactListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (ContactListBox.SelectedIndex == -1)
            return;

        currentSelectedListBoxItem = this.ContactListBox.ItemContainerGenerator.ContainerFromIndex(ContactListBox.SelectedIndex) as ListBoxItem;

        if (currentSelectedListBoxItem == null)
            return;

        // Iterate whole listbox tree and search for this items
        TextBox nameBox = helperClass.FindDescendant<TextBox>(currentSelectedListBoxItem);
        TextBlock nameBlock = helperClass.FindDescendant<TextBlock>(currentSelectedListBoxItem);

<强> helperFunction

public T FindDescendant<T>(DependencyObject obj) where T : DependencyObject
    {
        // Check if this object is the specified type
        if (obj is T)
            return obj as T;

        // Check for children
        int childrenCount = VisualTreeHelper.GetChildrenCount(obj);
        if (childrenCount < 1)
            return null;

        // First check all the children
        for (int i = 0; i < childrenCount; i++)
        {
            DependencyObject child = VisualTreeHelper.GetChild(obj, i);
            if (child is T)
                return child as T;
        }

        // Then check the childrens children
        for (int i = 0; i < childrenCount; i++)
        {
            DependencyObject child = FindDescendant<T>(VisualTreeHelper.GetChild(obj, i));
            if (child != null && child is T)
                return child as T;
        }

        return null;
    }

答案 1 :(得分:3)

使用此编辑功能,您还可以按名称搜索控件(从VB.NET转换):

public T FindDescendantByName<T>(DependencyObject obj, string objname) where T : DependencyObject
{
    string controlneve = "";

    Type tyype = obj.GetType();
    if (tyype.GetProperty("Name") != null) {
        PropertyInfo prop = tyype.GetProperty("Name");
        controlneve = prop.GetValue((object)obj, null);
    } else {
        return null;
    }

    if (obj is T && objname.ToString().ToLower() == controlneve.ToString().ToLower()) {
        return obj as T;
    }

    // Check for children
    int childrenCount = VisualTreeHelper.GetChildrenCount(obj);
    if (childrenCount < 1)
        return null;

    // First check all the children
    for (int i = 0; i <= childrenCount - 1; i++) {
        DependencyObject child = VisualTreeHelper.GetChild(obj, i);
        if (child is T && objname.ToString().ToLower() == controlneve.ToString().ToLower()) {
            return child as T;
        }
    }

    // Then check the childrens children
    for (int i = 0; i <= childrenCount - 1; i++) {
        string checkobjname = objname;
        DependencyObject child = FindDescendantByName<T>(VisualTreeHelper.GetChild(obj, i), objname);
        if (child != null && child is T && objname.ToString().ToLower() == checkobjname.ToString().ToLower()) {
            return child as T;
        }
    }

    return null;
}

答案 2 :(得分:2)

我不能给你一个完整的答案......

但我认为你可以使用VisualTreeHelper迭代任何控件的子代 http://blogs.msdn.com/b/kmahone/archive/2009/03/29/visualtreehelper.aspx

但是,对于您正在寻找的效果,我认为使用SelectedItem样式可能是更好的解决方案 - 例如请参阅此文章 - http://joshsmithonwpf.wordpress.com/2007/07/30/customizing-the-selected-item-in-a-listbox/

答案 3 :(得分:1)

使用ItemContainerGenerator

private void ContactListBox_SelectionChanged
  (object sender, SelectionChangedEventArgs e)
{
  if (e.AddedItems.Count == 1)
  {
    var container = (FrameworkElement)ContactListBox.ItemContainerGenerator.
                      ContainerFromItem(e.AddedItems[0]);

    StackPanel sp = container.FindVisualChild<StackPanel>();
    TextBox tbName = (TextBox) sp.FindName("tbName");
    TextBlock lblName = (TextBlock)sp.FindName("lblName");
    TextBlock lblNumber = (TextBlock)sp.FindName("lblNumber");
  }
}

答案 4 :(得分:1)

由于DataTemplate是一个可以在代码中多次使用的通用模板,因此无法通过名称访问它(x:Name =“numberTextBox”)。

我通过制作一系列控件解决了类似的问题 - 当Listbox填充时我将Textbox控件添加到集合中。

string text = myCollectionOfTextBoxes[listbox.SelectedIndex].Text; 

直到我找到了更好的灵魂 - 标签属性。在ListboxItem中,将Tag属性绑定到名称

Tag="{Binding Name}"

并访问它

ListBoxItem listBoxItem = ContactListBox.SelectedItem as ListBoxItem;

string name = listBoxItem.Tag.ToString();