Question

I"m trying to get my head wrapped around the WPF model.

I have a list box of items. Inside the list box items are string identifiers. This works fine. What I want is to have it so that the identifier from the currently selected item is accessible in my code-behind for the enclosing control.

I have this:

<ListBox.ItemTemplate>
 <DataTemplate>
   <StackPanel Width="320">
    <Label Content="{Binding Path=ShortName}" Style="{StaticResource ListHeader}"/>
      <TextBlock TextWrapping="Wrap" Text="{Binding Path=Description}" Style="{StaticResource ListText}" />
   </StackPanel>
 </DataTemplate>
 </ListBox.ItemTemplate>

And I think I should add something like:

<DataTemplate.Triggers>
    <DataTrigger Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ListBoxItem}},Path=IsSelected}" Value="True">
    <Setter Property="" TargetName="">
     <Setter.Value>

     </Setter.Value>
   </Setter>
 </DataTrigger>

But I'm lost as to how to set-up the setter to set a property that's part of the enclosing control (ie, the outside world). I think I have this backwards somehow?

Was it helpful?

Solution

If you are trying to access a property on a selected list box item from outside of the listbox then you can do the following in your code behind:

CustomItem item = (CustomItem)listBox1.SelectedItem;
MessageBox.Show(item.ShortName);

And your xaml is as follows:

<ListBox Height="100" Name="listBox1">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Name="stackPanel1">
                    <Label Content="{Binding Path=Shortname}"/>
                    <TextBlock Text="{Binding Path=Description}"/>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

You just cast the selecteditem from the listbox to your object type, then access the property on the object.

Hope this is what you were after.

OTHER TIPS

Have you tried using the SelectedValuePath property?

When you have a list of say Customers on the ItemsSource property, and you set the SelectedValuePath to Name, your SelectedValue property will return the name of the Customer in stead of the customer...

In your code behind, the SelectedValue will be the Name, the SelectedItem will return your Customer object.. in my example..

Hope this helps somehow..

Good luck!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top