I have a combobox which binds to ObservableCollection<CustomerViewModel>
<ComboBox ItemsSource="{Binding AllCustomers}" IsEditable="True"/>
If I use DisplayMemberPath property, the dropdown and the selecteditem displays correctly
<ComboBox ItemsSource="{Binding AllCustomers}" DisplayMemberPath="CustomerName" IsEditable="True"/>
But if a DataTemplate is assigned, the selecteditem is not displayed properly
<ComboBox ItemsSource="{Binding AllCustomers}" SelectedValue="CustomerName" IsEditable="True">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding CustomerName}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ComboBox>
Edit: I found the issue, but not the solution, and the issue is if the ComboBox has IsEditable="True" it creates the problem.
Code abstract:
public class AllCustomersViewModel
{
public ObservableCollection<CustomerViewModel> AllCustomers {get; set;}
}
public class CustomerViewModel
{
public string CustomerName;
public short CustomerID;
}
Which property is to be set (or how) to display the selectedvalue/item correctly.
Thank you very much in advance.
ActualCode
public class AccountTransactionsViewModel
{
DataRepository _repository;
public AccountTransactionsViewModel()
{
_repository = new DataRepository();
CreateAccountsViewModel();
}
public ObservableCollection<AccountViewModel> AllAccounts { get; set; }
void CreateAccountsViewModel()
{
List<AccountViewModel> allAccounts = _repository.GetAccounts()
.Select(a => new AccountViewModel(a, _repository))
.ToList();
AllAccounts = new ObservableCollection<AccountViewModel>(allAccounts);
}
}
public class AccountViewModel
{
Account _account;
DataRepository _repository;
public AccountViewModel(Account account, DataRepository repository)
{
_account = account;
_repository = repository;
}
public short AccountID { get { return _account.AccountID; } set { } }
public string AccountName { get { return _account.AccountName; } set { } }
}
XAML:
<ComboBox Name="customerCombobox" ItemsSource="{Binding AllAccounts}" IsEditable="True">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding AccountName}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ComboBox>
Edit:
I found the issue, but not the solution, and the issue is if the ComboBox has IsEditable="True" it creates the problem.
AccountName
in code andCustomerName
in XAML. Can you post your actual code? Because setting theItemTemplate
should effect the also the selected item as well and your code should work. – nemesv