views:

213

answers:

2

Hi,

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?

+1  A: 

Hi there,

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.

Blounty
Sorry the selected item isn't of a custom class, it's a StackPanel as included in the ListBox.ItemTemplate above
evilfred
Hi EvilFred, I set up my Xaml exactly as yours, but you are binding a collection of objects to the itemsource property of the listbox i presume. Ithe selecteditem property of the listbox gives you access to the bound object selectd not the UI elements.
Blounty
oh duh, I see. the magical separation of UI from non-UI elements people keep talking about in WPF. thanks!
evilfred
+1  A: 

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!

Arcturus