I want to bind a value of each object stored in a ObersvableCollection to the ComboBox. Unfortunately it doesn't work.
<ComboBox Grid.Column="1" Margin="0,0,0,5" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" FontSize="15" ItemsSource="{Binding Path=UserAccounts}" >
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding EMailAddress}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
In the code behind I set the DataContext:
this.DataContext = PersitentDataModelUserSettings.Instace.UserAccounts;
Here is the Model:
public class PersitentDataModelUserSettings : ModelBase
{
private static PersitentDataModelUserSettings instance = new PersitentDataModelUserSettings();
public static PersitentDataModelUserSettings Instance
{
get { return instance; }
set { instance = value; }
}
private ObservableCollection<AccountSettingsObj> _userAccounts = new ObservableCollection<AccountSettingsObj>();
public ObservableCollection<AccountSettingsObj> UserAccounts
{
get { return _userAccounts; }
set
{
_userAccounts = value;
OnPropertyChanged("UserAccounts");
}
}
}
This is the object type:
[XmlRoot]
public class AccountSettingsObj : ModelBase
{
public string FirstName { get; set; }
public string LastName { get; set; }
private string _eMailAddress;
public string EMailAddress
{
get { return _eMailAddress; }
set
{
_eMailAddress = value;
OnPropertyChanged("EMailAddress");
}
}
}
Thanks!
You are setting ItemSource of comboBox to this:
ItemsSource="{Binding Path=UserAccounts}"
but you also setting DataContext of ComboBox to this:
this.DataContext = PersitentDataModelUserSettings.Instace.UserAccounts;
So binding engine is looking for property UserAccounts
in UserAccounts
.
This can be fixed in two ways:
Either set ItemsSource to binding like this: ItemsSource="{Binding}"
. This way you are saying ItemSource
is same as DataContext
of ComboBox.
Or set DataContext to instance only : this.DataContext = PersitentDataModelUserSettings.Instace.UserAccounts;
. This way you set DataContext to point to instance of PersitentDataModelUserSettings and asking BindingEngine to look for property UserAccounts in PersitentDataModelUserSettings .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.