I have read a couple of other articles, but none have been able to answer my combination of issues
我有一个ComboBox,我想在其中显示不同颜色的项目,这可以通过使用ComboBoxItem并设置其背景来完成 . 当我想以不同的颜色存储我的CategoryDTO并稍后能够再次提取它时,我的问题出现了 . 我需要显示的只是我的CategoryDTOs的颜色和Name属性 . 然后我必须能够从SelectedItem属性中获取CategoryDTO对象 . 我使用ItemsSource,DisplayMemberPath和SelectedValuePath尝试了各种解决方案 . 但是只完成了这个
如图所示它显示颜色,但只显示所选CategoryDTO的名称,我甚至还没有测试过SelectedItem是否正常工作 . 下面我将把我使用的代码 .
[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时,我当然会扩展我对这个问题的了解,但是现在我希望这可以工作 .
This is not homework
EDIT: forgot to list errors i also get
System.Windows.Data错误:4:无法找到绑定源,引用'RelativeSource FindAncestor,AncestorType ='System.Windows.Controls.ItemsControl',AncestorLevel ='1'' . BindingExpression:路径= HorizontalContentAlignment;的DataItem = NULL; target元素是'CategoryComboBoxItem'(Name =''); target属性为'HorizontalContentAlignment'(类型'HorizontalAlignment')System.Windows.Data错误:4:无法找到绑定源,引用'RelativeSource FindAncestor,AncestorType ='System.Windows.Controls.ItemsControl',AncestorLevel ='1'' . BindingExpression:路径= VerticalContentAlignment;的DataItem = NULL; target元素是'CategoryComboBoxItem'(Name ='');目标属性是'VerticalContentAlignment'(类型'VerticalAlignment')System.Windows.Data错误:26:ItemConmplate和ItemTemplateSelector被ItemsControl的容器类型的项目忽略;类型= 'CategoryComboBoxItem'
1 回答
要使用WPF正确执行此操作,我认为您需要更好地了解
DataContext
及其工作原理 . 我写了一篇博文,只是为了链接SE:What is this "DataContext" you speak of? . 我强烈建议您在使用WPF做任何事情之前确保理解DataContext
.您的整体想法是要将
ComboBox
绑定到CategoryDTO
项目列表,并将SelectedValue
属性设置为Name
.如果正确设置了DataContext,则可以使用绑定为ComboBox设置项目
或者代码背后
这也会使您的
ComboBox.SelectedItem
与列表中所选的CategoryDTO
项同步,因此您可以直接将其投射到使用它的位置或绑定它,以便从DataContext中使用它
注意:根据
.Color
属性的数据类型,您可能需要使用Converter
将.Color
值转换为.Background
,以获取.Background
属性 . 应该有很多在线转换器的例子,或者只是询问你是否需要帮助 .