Can you associate a selected item in a list with a single object in WPF?

If I have two objects, one of which is a list of elements and the other having a property that saves the selected element of the other list, is it possible to update the selected element by binding in WPF?

Suppose I have these two data structures:

public class MyDataList { public ObservableCollection<Guid> Data { get; set; } } public class MyDataStructure { public Guid ChosenItem { get; set; } } 

Is it possible to associate a Listbox with an instance of both objects so that the ChosenItem property is set by the selected ListBox?

EDIT. To make things clearer, there can be many instances of MyDataStructure, each of which has a selected item from MyDataList. The data list is common to all instances, and I need a way to select an item and save that selection to MyDataStructure.

+3
source share
2 answers

I believe you should do this (be sure to declare a local namespace):

 <Window.Resources> <local:MyDataStructure x:Key="mds1" /> </Window.Resources> <ListBox ItemsSource="{Binding Data}" SelectedValue="{Binding Source={StaticResource mds1} Path=ChosenItem}"/> 
+2
source

Make these two properties inside the same class (just to simplify the solution) and make the code ready for the properties of changed events

  public class MyDataList : INotifyPropertyChanged { private Guid _choosen; public ObservableCollection<Guid> Data { get; set; } public Guid ChosenItem { get { return _choosen; } set { _choosen = value; PropertyChanged(this, new PropertyChangedEventArgs("ChosenItem")); } } public event PropertyChangedEventHandler PropertyChanged; } 

create an instance of this class and bind to the DataContext ListBox Now write the ListBox XAML code, as shown below. Binding SelectedValue does the trick here.

 <ListBox ItemsSource="{Binding Data}" SelectedValue="{Binding Path=ChosenItem}" x:Name="listBox"/> 
+1
source

All Articles