views:

498

answers:

1

Hello,

The combobox items are taken from one table, one field on which binding is made. After I saved in the database the selected item in another table, I want that the selected item to be the one which was saved. But the selected item is lost. So, my question is: can I bind the combobox to two DataContexts or maybe another solution ?.

To give an example to be more clear: the combobox items are predefined values taken from a datasource and the value selected must be saved and shown on the interface. So, from what I can see must be a binding to the predefined values and also a binding to the value saved to make a connection to the selected item.

Any suggestion?

+1  A: 

Ioana, I don't seem to get what you're aiming at..
if you take this xaml:

<Window x:Class="WpfApplication4.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window1"
        Height="300"
        Width="300">
    <StackPanel>
        <TextBox Text="{Binding Path=SelectedText, Mode=TwoWay}" 
                 Width="200"/>
        <ComboBox Width="200"
                  VerticalAlignment="Center"
                  HorizontalAlignment="Center"
                  SelectedItem="{Binding Path=SelectedText, Mode=TwoWay}"
                  ItemsSource="{Binding Path=Texts, Mode=OneWay}">
        </ComboBox>
    </StackPanel>
</Window>

and this codebehind:

    public partial class Window1 : INotifyPropertyChanged
    {
        public Window1()
        {
            InitializeComponent();
            this.Texts = new List<string>(new[] {"foo","bar"});
            this.DataContext = this;
        }

    private ObservableCollection<string> texts;
    public ObservableCollection<string> Texts 
    { 
        get
        {
            return texts;
        }

        set
        {
            texts = value;
            if (this.PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs("Texts"));
        }
    }

    private string selectedText;
    public string SelectedText
    {
        get
        {
            return selectedText;
        }

        set
        {
            selectedText = value;
            if (this.PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs("SelectedText"));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

You do have the Items and the selectedValue databound.
Notice the INotifyPropertyChanged.
Is this what you're trying to achieve ?

Nils
Although it was not asked, if you also want to be able to update the Items, you have to make sure Texts sends also a PropertyChangedEvent if modified.
Wimmel
yes, I modified the code...
Nils