【发布时间】:2020-12-06 02:10:38
【问题描述】:
我在将“复杂”组合框转换为同样复杂的自动完成框时遇到了一些麻烦。我的目标是能够选择并将 ShoppingCart 的项目设置为类似于列表中的项目之一。这是重现我的情况的三个步骤(我正在使用 Stylet 及其 SetAndNotify() INPC 方法):
-
创建两个对象,一个只有一个 Name 属性,另一个只有另一个对象作为属性
public class ItemModel : PropertyChangedBase { private string _name; public string Name { get => _name; set => SetAndNotify(ref _name, value); } } public class ShoppingCartModel : PropertyChangedBase { public ItemModel Item { get; set; } } -
初始化并填充 DataContext 中的 ItemsList 和 Shoppingcart(因为我们使用的是 MVVM,所以它是 ViewModel)
public ShoppingCartModel ShoppingCart { get; set; } public ObservableCollection<ItemModel> ItemsList { get; set; } public ShellViewModel() { ItemsList = new ObservableCollection<ItemModel>() { new ItemModel { Name = "T-shirt"}, new ItemModel { Name = "Jean"}, new ItemModel { Name = "Boots"}, new ItemModel { Name = "Hat"}, new ItemModel { Name = "Jacket"}, }; ShoppingCart = new ShoppingCartModel() { Item = new ItemModel() }; } -
在 View 中创建 AutoCompleteBox、ComboBox 和一个小 TextBlock 以对其进行全面测试:
<Window [...] xmlns:toolkit="clr-namespace:System.Windows.Controls;assembly=DotNetProjects.Input.Toolkit"> <!-- Required Template to show the names of the Items in the ItemsList --> <Window.Resources> <DataTemplate x:Key="AutoCompleteBoxItemTemplate"> <StackPanel Orientation="Horizontal" HorizontalAlignment="Center" Background="Transparent"> <Label Content="{Binding Name}"/> </StackPanel> </DataTemplate> </Window.Resources> <StackPanel> <!-- AutoCompleteBox: can see the items list but selecting doesn't change ShoppingCart.Item.Name --> <Label Content="AutoCompleteBox with ShoppingCart.Item.Name as SelectedItem:"/> <toolkit:AutoCompleteBox ItemsSource="{Binding ItemsList}" ValueMemberPath="Name" SelectedItem="{Binding Path=ShoppingCart.Item.Name}" ItemTemplate="{StaticResource AutoCompleteBoxItemTemplate}"/> <!-- ComboBox: can see the items list and selecting changes ShoppingCart.Item.Name value --> <Label Content="ComboBox with ShoppingCart.Item.Name as SelectedValue:"/> <ComboBox ItemsSource="{Binding ItemsList}" DisplayMemberPath="Name" SelectedValue="{Binding Path=ShoppingCart.Item.Name}" SelectedValuePath="Name" SelectedIndex="{Binding Path=ShoppingCart.Item}" /> <!-- TextBox: Typing "Jean" or "Jacket" updates the ComboBox, but not the AutoCompleteBox --> <Label Content="Value of ShoppingCart.Item.Name:"/> <TextBox Text="{Binding Path=ShoppingCart.Item.Name}"/> </StackPanel> </window>
将 AutoCompleteBox 的 SelectedItem 的绑定模式更改为 TwoWay 使其打印“[ProjectName].ItemModel”,这意味着 (我猜?) 它正在获取 ItemModels 而不是字符串,但我似乎无法让它工作。任何帮助将不胜感激,谢谢,如果可以缩小我的帖子,请随时编辑。
【问题讨论】:
标签: c# wpf xaml wpftoolkit autocompletebox