1
votes

I am having trouble binding selected item of a ListBox in my application (IDE : Visual Studio 2010, Language : C#, Technology : WPF and MVVM).

Requirement: There is a list of interfaces and another list of devices connected to each interface. The pattern of displaying these 2 lists is as follows:

Interface 1

Device 1

Device 2

Device 3

Interface 2

Device 1

Device 2

Interface 3

Device 1

Device 2

Device 3

Device 4

and so on.

If any interface is selected then by default the first device must be selected and if any device is selected then the corresponding interface must be selected. I am able to do the first part but not the second part. How can I make the selected Item to be unique across all the inner list of devices?

I want to display the above list as a list of expanders where each exapander will have the following format: Expander header : Interface name Expander Body : List of connected devices

I hope I am clear.

Please do tell me if there is any wpf control for this or should I develop a new ListBox for this?

Regards Kruthika

1

1 Answers

0
votes

According to this requirement :

How can I make the selected Item to be unique across all the inner list of devices?

You should just define groups in one big listbox :

public class Interface
{
    public string Name { get; set; }
    public List<Device> Devices { get; set; }
}

public class Device
{
    public string Name { get; set; }
}

<CollectionViewSource x:Key="interfaces" Source="{Binding SomePropertyGivingInterfaces}" >
    <CollectionViewSource.GroupDescriptions>
        <PropertyGroupDescription PropertyName="Name" />
    </CollectionViewSource.GroupDescriptions>
</CollectionViewSource>

<DataTemplate x:Key="interfaceTemplate" DataType="Interface">
    <StackPanel Orientation="Horizontal">
        <TextBlock Text="{Binding Name}" />
    </StackPanel>
</DataTemplate>

<ListBox ItemsSource="{Binding Source={StaticResource interfaces}}">
    <ListBox.GroupStyle>
        <GroupStyle HeaderTemplate="{StaticResource interfaceTemplate}" />
    </ListBox.GroupStyle>
    <ListBox.ItemTemplate>
        <DataTemplate DataType="Device">
            <ListBox ItemsSource="{Binding Devices}">
                <ListBox.ItemTemplate>
                    <DataTemplate DataType="Device">
                        <TextBlock Text="{Binding Name}" />
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Then when you can only select one device.