Misha Zaslavsky
Misha Zaslavsky

Reputation: 9702

Bind ListBox to SelectionChanged ComboBox in XAML

I want to bind the selection change of the combo box to update my list box, but my xaml code is probably wrong.

This is my Collection that takes the data from the Service.

public class WorkersCollection
{
    private WorkerClient client = new WorkerClient();
    public ObservableCollection<Worker> Workers { get; set; }

    public WorkersCollection()
    {
        Workers = new ObservableCollection<Worker>();
    }

    public ICollection<Worker> GetAllWorkers()
    {
        foreach (var worker in client.GetAllWorkers())
        {
            Workers.Add(worker);
        }

        return Workers;
    }
}

My DataContext is workers:

public partial class MainWindow : Window
{
    WorkersCollection workers;

    public MainWindow()
    {
        InitializeComponent();

        workers = new WorkersCollection();
        this.DataContext = workers;

        workers.GetAllWorkers();
    }
}

and in XAML:

<ComboBox Name="cbxWorkers" HorizontalContentAlignment="Right" SelectedItem="{Binding Workers}" ItemsSource="{Binding Workers}">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <ComboBoxItem Content="{Binding LastName}" />
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

<ListBox Grid.Row="3" ItemTemplate="{StaticResource WorkersTemplate}" ItemsSource="{Binding ElementName=cbxWorkers, Path=SelectedItem}" />

How can I fix it?

Upvotes: 0

Views: 965

Answers (1)

kmatyaszek
kmatyaszek

Reputation: 19296

ItemsSource property of class ListBox has type IEnumerable (msdn).

So you can't assign to it object of type Worker.

You can create converter to do that.

Converter class:

public class WorkerToListConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return new List<Worker> { value as Worker };
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

XAML code:

...
<Window.Resources>
        <local:WorkerToListConverter x:Key="myCon" />
</Window.Resources>    
...
<ComboBox Name="cbxWorkers" HorizontalContentAlignment="Right" ItemsSource="{Binding Workers}">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <ComboBoxItem Content="{Binding LastName}" />
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

<ListBox Grid.Row="3" ItemTemplate="{StaticResource WorkersTemplate}" 
         ItemsSource="{Binding ElementName=cbxWorkers, Path=SelectedItem, Converter={StaticResource myCon}}" />
...

You should also delete SelectedItem binding from ComboBox.

   ... SelectedItem="{Binding Workers}" ItemsSource="{Binding Workers}" ...

It's no sense to binding SelectedItem to the same thing as ItemsSource.

Upvotes: 1

Related Questions