我有一个绑定到的组合框ObservableCollection<CustomerViewModel>
<ComboBox ItemsSource="{Binding AllCustomers}" IsEditable="True"/>
如果我使用 DisplayMemberPath 属性,下拉列表和选定项会正确显示
<ComboBox ItemsSource="{Binding AllCustomers}" DisplayMemberPath="CustomerName" IsEditable="True"/>
但是如果分配了DataTemplate,则所选项目无法正确显示
<ComboBox ItemsSource="{Binding AllCustomers}" SelectedValue="CustomerName" IsEditable="True">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding CustomerName}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ComboBox>
编辑:我找到了问题,但没有找到解决方案,问题是如果 ComboBox 具有 IsEditable="True" 它会产生问题。
代码摘要:
public class AllCustomersViewModel
{
public ObservableCollection<CustomerViewModel> AllCustomers {get; set;}
}
public class CustomerViewModel
{
public string CustomerName;
public short CustomerID;
}
要设置(或如何)哪个属性以正确显示选定的值/项目。
非常感谢您提前。
实际代码
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>
编辑:
我找到了问题,但没有找到解决方案,问题是如果 ComboBox 具有 IsEditable="True" 它会产生问题。