Reputation: 1373
Im trying to set default value of ComboBox
. I'm using binding in layout and I'm not sure how bind it right. Here is my viewModel
:
public class ViewModel : INotifyPropertyChanged
{
private Sklady sklady = null;
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
public Sklady Sklady
{
get
{
return this.sklady;
}
set
{
this.sklady = value;
NotifyPropertyChanged("Sklady");
}
}
}
How I am set data to viewModel
:
private void comboBoxSklad_Loaded(object sender, RoutedEventArgs e)
{
//get some data
prijemWindow.viewModel.Sklady = sklady;
prijemWindow.viewModel.Sklady.skladID = prijemWindow.viewModel.Radky.radky[index].SKLAD;
}
My viewModel
use this class to get values:
[DataContract]
public class Sklady
{
[DataMember]
public List<Sklad> sklady { get; set; }
[DataMember]
public String skladID { get; set; }
public class Sklad
{
public string ID { get; set; }
public string NAME { get; set; }
public string CODE { get; set; }
}
}
And this is current xaml
code:
<ComboBox Name="comboBoxSklad" Loaded="comboBoxSklad_Loaded" ItemsSource="{Binding Sklady.sklady}" DisplayMemberPath="CODE"
SelectedValuePath="ID" SelectedItem="{Binding Sklady.skladID}"/>
Data are binded into ComboBox
correctly and I can see data from sklady
List
. But I would like to set the ComboBox
default value to skladID
value. How can I do it?
ANSWER
With answer from Klaus Byskov Pedersen
I get it work... First, I use SelectedValue
instead of SelectedItem
... Then, I ininialize Sklady
in constructor prijemWindow.viewModel.Sklady = new Sklady();prijemWindow.viewModel.Sklady = new Sklady();
and at the end, changed lines :
sklady.skladID = prijemWindow.viewModel.Radky.radky[index].SKLAD;
prijemWindow.viewModel.Sklady = sklady;
Thanks a lot!
Upvotes: 0
Views: 87
Reputation: 121067
Use SelectedValue
instead of SelectedItem
.
<ComboBox Name="comboBoxSklad" Loaded="comboBoxSklad_Loaded" ItemsSource="{Binding Sklady.sklady}" DisplayMemberPath="CODE"
SelectedValuePath="ID" SelectedValue="{Binding Sklady.skladID}"/>
When using SelectedItem
the bound item would be of type Sklady
, not string
.
EDIT`
prijemWindow.viewModel.Sklady = sklady;
prijemWindow.viewModel.Sklady.skladID = prijemWindow.viewModel.Radky.radky[index].SKLAD;
You have a NotifyPropertyChanged
when you set viewModel.Sklady
but at the time this is fired, you have not yet set the skladID
so try changing the order of those two statements.
Upvotes: 2