Hi,

I have a question regarding navigating to a listbox item in C#. I have written code which populates a listbox from an xml file in xaml (thus bound to it). However I want to navigate to the selected item in the listbox using code in c#. I can navigate through the xml document without issues but how do I call the specific item that is selected in the listbox? For example, the listbox has items populated from the xml at node 1 and node 2 respectively: "Coffee" {i.e node1}, "Cream" {i.e node2}. By selecting 'Coffee', how can I specify this in the C# code?

For more info here is part of the xaml code:

<ListBox x:Name="lbRecipe2" Height="auto" Width="150" BorderBrush="Blue"  IsSynchronizedWithCurrentItem="True"
                     ItemsSource="{Binding ElementName=lbRecipe, Path=SelectedItem, Mode=OneWay}" SelectionChanged="lbRecipe2_SelectionChanged" >
                            <ListBox.ItemTemplate>
                                <DataTemplate>
                                    <StackPanel Height="auto">
                                        <TextBlock FontWeight="Bold" FontSize="12" Text="{Binding XPath=name}" />
                                        <TextBlock FontSize="11" Text="{Binding XPath=summary}" />
                                    </StackPanel>
                                </DataTemplate>
                            </ListBox.ItemTemplate>
                        </ListBox> 

And here is part of the c# code {note the lbrecipe2. which is incomplete): 

        private void AddButton_Click(object sender, RoutedEventArgs e)
        {
            if (lbRecipe2.Items.GetItemAt == "")
            {

            }
        }

Any help is greatly appreciated.

Thanks

Recommended Answers

All 2 Replies

This is how you get selected item from a listBox:

private void PopulatingListBox()
        {
            string[] ar = new string[] { "Coffee", "Cream" };
            listBox1.Items.AddRange(ar);
        }
 
         private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            string item = this.listBox1.SelectedItem.ToString();
            MessageBox.Show("Selected item is : " + item);
        }

Hope it helps,

Mitja

Thanks Mitja, that definitely helped.

However I have another question. I can locate the value of an xml element such as <element>value</element>. How can I locate the attribute value of an element such as <element attribute="value" />?

Thanks again.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.