views:

47

answers:

1

I have the following XAML:

<ComboBox Height="23" HorizontalAlignment="Left" Grid.Row="6" Grid.Column="2"
          Name="cbo_team" VerticalAlignment="Top" Width="148"
          DataContext="{Binding ElementName=cbo_component, Path=SelectedItem}"
          SelectedIndex="0">
    <ComboBox.ItemsSource>
        <Binding XPath="Teams/Team/@id"
                 Converter="{StaticResource xmlConverter}">
            <Binding.ConverterParameter>
                <local:XmlConverterParameter
                    XPathTemplate="/Products/Teams/Team[{0}]"
                    XPathCondition="@id='{0}'" />
            </Binding.ConverterParameter>
        </Binding>
    </ComboBox.ItemsSource>
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding XPath=@name}" />
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

In C#, I'm trying to get the value of the TextBlock that is in the current selected item in the ComboBox. How do I do that? This question is pretty much the same, but the only answer doesn't help.

A: 

Check this sample out. The textblock (below the combobox) is showing the value of the name attribute of the currently selected xml element in the combobox. A message box will popup with the same result from the lookup in the visual tree. The lookup fails on initial selection changed. Looks like comboboxitems are created after selected item is set.

XAML:

<Window x:Class="CBTest.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Height="300" Width="300">

    <Window.Resources>
        <XmlDataProvider x:Key="UsersData" XPath="Users">
            <x:XData>
                <Users xmlns="">
                    <User name="Sally" />
                    <User name="Lucy" />
                    <User name="Linus" />
                    <User name="Charlie" />
                </Users>
            </x:XData>
        </XmlDataProvider>
    </Window.Resources>

    <StackPanel>

        <ComboBox 
            Name="_comboBox"
            ItemsSource="{Binding Source={StaticResource UsersData},XPath=*}"
            SelectedIndex="0"
            SelectionChanged="OnComboBoxSelectionChanged">
            <ComboBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding XPath=@name}" Name="nameTextBlock" />
                </DataTemplate>
            </ComboBox.ItemTemplate>
        </ComboBox>

        <!-- Below shows how to get the value of selected item directly from the data. -->
        <TextBlock 
            DataContext="{Binding Path=SelectedItem, ElementName=_comboBox}"
            Text="{Binding XPath=@name}" />

    </StackPanel>

</Window>

Code behind, showing how to get the text directly by traversing the visual tree:

private void OnComboBoxSelectionChanged(object sender, SelectionChangedEventArgs e)
{
    ComboBox comboBox = sender as ComboBox;
    ComboBoxItem comboBoxItem = comboBox.ItemContainerGenerator.ContainerFromItem(comboBox.SelectedItem) as ComboBoxItem;
    if (comboBoxItem == null)
    {
        return;
    }
    TextBlock textBlock = FindVisualChildByName<TextBlock>(comboBoxItem, "nameTextBlock");
    MessageBox.Show(textBlock.Text);
}

private static T FindVisualChildByName<T>(DependencyObject parent, string name) where T : DependencyObject
{
    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
    {
        var child = VisualTreeHelper.GetChild(parent, i);
        string controlName = child.GetValue(NameProperty) as string;
        if (controlName == name)
        {
            return child as T;
        }
        T result = FindVisualChildByName<T>(child, name);
        if (result != null)
            return result;
    }
    return null;
}
Wallstreet Programmer
It seems like an unnecessary workaround to have a secondary field showing the contents of the selected item in the ComboBox, just for the purpose of being able to read that secondary field in C#. I'll keep this in mind, though, as kind of an ugly hack.
Sarah Vessels
I just added that textblock in the sample to show you how to get the name attribute from selected item. The textblock is not needed. Are you confusing it with the textblock used in the datatemplate for combobox items?
Wallstreet Programmer
Oh, gotcha. When I check the `SelectedItem` property in C#, I get an XML structure. I can check the `Attributes` property on there and extract the value of the `name` attribute in C#, but that seems redundant because the `name` attribute is already extracted in the XAML--it's what shows up in the `TextBlock`. It seems like I should be able to extract a simple string value--the `name` attribute shown in the `TextBlock`--from the `ComboBox` without having to worry about the XML structure from whence that value came.
Sarah Vessels
The problem is that you don't have a reference to the selected combobox item's textblock. You need to use code behind to search for it in the visual tree. I edited my answer to show this (less elegant) approach as well.
Wallstreet Programmer