views:

2022

answers:

2

If I have two objects, one being the list of items, and the other having a property storing the selected item of the other list, is it possible to update the selected item through binding in WPF?

Lets say 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 bind a Listbox to an instance of both objects so that the ChosenItem property gets set by the selected item of the ListBox?

EDIT: To make things a bit clearer, there might be many instances of MyDataStructure, each with a chosen item from MyDataList. The data list is common to all the instances, and I need a way to select an item and store that selection in the MyDataStructure.

+1  A: 

Make this two properties inside a single class(Just to simplify the solution) and make the code ready for property 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 of the ListBox Now write the ListBox XAML code as bellow. SelectedValue binding is doing the trick here.

<ListBox ItemsSource="{Binding Data}" SelectedValue="{Binding Path=ChosenItem}" x:Name="listBox"/>
Jobi Joy
Not really possible. I might have several Chosen items in different listboxes, where the items are coming from the same source but the chosen item will be different.
Cameron MacFarland
But the catch here is using SelectedValue Binding. The DataArchitecture can be anyway way as you wanted.
Jobi Joy
+1  A: 

I believe you should be able to do this (make sure to declare the local namespace):

<Window.Resources>
    <local:MyDataStructure x:Key="mds1" />
</Window.Resources>    
<ListBox ItemsSource="{Binding Data}" SelectedValue="{Binding Source={StaticResource mds1} Path=ChosenItem}"/>
thealliedhacker
Yep that worked. Is it possible to do without using the Static Resource though?
Cameron MacFarland