[Serializable]
public class CategoryDTO
{
public string Name { get; set; }
...not important...
}
CategoryDTO[] categories = await _isd.GetCategoriesAsync();
comboBoxCategory.ItemsSource = categories.Select(c => new CategoryComboBoxItem(c)).ToList();
comboBoxCategory.DisplayMemberPath = "Name";
comboBoxCategory.SelectedValuePath = "Name";
public class CategoryComboBoxItem : ComboBoxItem
{
public CategoryComboBoxItem(CategoryDTO category)
{
this.Background = new SolidColorBrush(category.Color);
this.Content = category;
}
}
我没有在.xaml中指定任何特殊的内容,所以我将省略该部分。除此之外,我希望能够使用Name属性设置SelectedItem。我非常希望答案在代码后面,但如果它愚蠢地复杂,只有xaml的答案也一样好。我没有MVVM的任何经验,我可以假设它会被建议。随着我对WPF的深入研究,我当然会扩展我在这方面的知识,但现在我只想让它发挥作用
这不是家庭作业
编辑:忘记列出我也会遇到的错误
系统.Windows。数据错误:4:无法找到引用“RelativeSource FindAncestor,AncestorType=”System.Windows.Controls的绑定源。ItemsControl',AncestorLevel=“1”
BindingExpression:Path=HorizontalContentAlignment;数据项=空;目标元素是“CategoryComboBoxItem”(名称=“”);目标属性是“HorizontalContentAlignment”(类型为“HorigintalAlignment)System.Windows。数据错误:4:无法找到引用“RelativeSource FindAncestor,AncestorType=”System.Windows.Controls的绑定源。ItemsControl',AncestorLevel=“1”
BindingExpression:Path=VerticalContentAlignment;数据项=空;目标元素是“CategoryComboBoxItem”(名称=“”);目标属性是“VerticalContentAlignment”(类型为“Vertical Alignment)System.Windows。数据错误:26:对于已经属于ItemsControl容器类型的项,忽略了ItemTemplate和ItemTemplateSelector;类型=“CategoryComboBoxItem”
要使用WPF正确地做到这一点,我认为您需要更好地了解DataContext
及其工作原理。我写了一篇博客文章只是为了在SE上链接:你说的“DataContext”是什么?。我强烈建议您在使用WPF做任何事情之前确保您了解DataContext
。
您的总体想法是要将< code>ComboBox绑定到< code > category to 项的列表,并将< code>SelectedValue属性设置为< code>Name。
<!-- create a ComboBox -->
<ComboBox x:Name="MyComboBox" SelectedValuePath="Name">
<!-- Add a custom Style to the individual items in combobox -->
<ComboBox.ItemContainerStyle>
<!-- In custom style, bind background color -->
<Style TargetType="{x:Type ComboBoxItem}">
<Setter Property="Background" Value="{Binding Color}"/>
</Style>
</ComboBox.ItemContainerStyle>
</ComboBox>
如果数据上下文设置正确,则可以使用绑定为 ComboBox 设置项
<ComboBox ItemsSource="{Binding CategoryList}" ..>
或者隐藏代码
MyComboBox.ItemsSource = CategoryList;
这也将同步您的< code >组合框。在列表中选择带有所选< code>CategoryDTO项目的edItem,这样您就可以直接对它进行强制转换以对其执行某些操作
CategoryDTO selected = (CategoryDTO)MyComboBox.SelectedItem;
DoSomethingWithSelected(selected);
或绑定它,以便从DataContext中轻松使用
<ComboBox SelectedItem="{Binding SelectedCategory}" ..>
// Can now use SelectedCategory directly
DoSomethingWithSelected(SelectedCategory);
注意:取决于<code>的数据类型。颜色属性,您可能需要使用Converter
来转换。将
值设置为
属性。网上应该有很多转换器的例子,或者问问你是否需要帮助。SolidColorBrush
。背景