Search code examples
c#wpfxamllistboxlistboxitem

How do i get a property from a selected ListBox Control 's listboxitem ? C#


like the title said i want to get the value of a property from a selected listboxitem on a button click

 <ListBox x:Name="IconListbox" Background="{x:Null}" BorderBrush="Black">
        <ListBox.ItemsPanel>
            <ItemsPanelTemplate>
                <StackPanel Orientation="Horizontal"/>
            </ItemsPanelTemplate>
        </ListBox.ItemsPanel>
        <ListBoxItem x:Name="defaultIcon">
            <Grid Background="Black">
                <Border BorderBrush="#FF1EF3F3" BorderThickness="2">
                    <Image x:Name="defaultIconImage" Width="50" Height="50" Source="icon.png"/>
                </Border>
            </Grid>
        </ListBoxItem>
        <ListBoxItem>
            <Grid Background="Black">
                <Border BorderBrush="#FF1EF3F3" BorderThickness="2">
                    <Image x:Name="secondIconImage" Width="50" Height="50" Source="SecondIcon.png"/>
                </Border>
            </Grid>
        </ListBoxItem>
    </ListBox>

For example if i click the button it should return the image source of the current selected item. So if ListboxItem defaultIcon is selected it should return defaulticon.png. How can i do this ?

Edit:

Maybe i am taking the wrong aproach by trying to use a listbox. I'm verry new to Xaml code and i'll try to better explain what i want as a result.

Here is a picture that i will use to try and explain: Image

So what i want is when 1 is selected i need it to return the source of the blue flame image when i click the save button

when 2 is selected i need it to return the source of the blue facebook image when i click the save button


Solution

  • You can find the Image inside SelectedItem like the code below

            var selectedItem = IconListbox.SelectedItem as ListBoxItem;
            if (selectedItem != null)
            {
                var image = selectedItem.GetChildOfType<Image>();
                if (image != null)
                {
                    var source = image.Source;
                }
            }
    

    extension method to get child of specific type

         public static T GetChildOfType<T>(this DependencyObject depObj) where T : DependencyObject
            {
                if (depObj == null) return null;
    
                for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
                {
                    var child = VisualTreeHelper.GetChild(depObj, i);
    
                    var result = (child as T) ?? GetChildOfType<T>(child);
                    if (result != null) return result;
                }
                return null;
            }