gpt4 book ai didi

c# - WPF-MVVM-组合框选定项

转载 作者:可可西里 更新时间:2023-11-01 02:59:19 24 4
gpt4 key购买 nike

我有 ViewModel (已实现 INotifyPropertyChanged )在后台和类中 Category它只有一个 string 类型的属性.我的 ComboBox SelectedItem 绑定(bind)到类别的实例。当我更改实例的值时,SelectedItem 不会更新,Combobox 也不会更改。

编辑:代码

组合框:

<ComboBox x:Name="categoryComboBox" Grid.Column="1"  Grid.Row="3" Grid.ColumnSpan="2" 
Margin="10" ItemsSource="{Binding Categories}"
DisplayMemberPath="Name" SelectedValue="{Binding NodeCategory, Mode=TwoWay}"/>

属性:

private Category _NodeCategory;
public Category NodeCategory
{
get
{
return _NodeCategory;
}
set
{
_NodeCategory = value;
OnPropertyChanged("NodeCategory");
}
}

[Serializable]
public class Category : INotifyPropertyChanged
{
private string _Name;
[XmlAttribute("Name")]
public string Name
{
get
{
return _Name;
}
set
{
_Name = value;
OnPropertyChanged("Name");
}
}

public void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}

[field:NonSerialized]
public event PropertyChangedEventHandler PropertyChanged;
}

我正在尝试的是:当我设置

NodeCategory = some_list_of_other_objects.Category;

Combobox 中选择该项目与适当的 DisplayMemberPath

最佳答案

您在此行中设置的类别 -

NodeCategory = some_list_of_other_objects.Category;

和您的类别集合中的一个 (ItemsSource="{Binding Categories}") 应该指的是同一个对象。如果不是,则 SelectedItem 将不起作用。

解决方案1-

您也可以像这样尝试使用 SelectedValuePath -

<ComboBox x:Name="categoryComboBox" 
ItemsSource="{Binding Categories}"
DisplayMemberPath="Name"
SelectedValuePath="Name"
SelectedValue="{Binding NodeCategory, Mode=TwoWay}" />

在代码中你可以做这样的事情-

private string _NodeCategory;
public string NodeCategory
{
get
{
return _NodeCategory;
}
set
{
_NodeCategory = value;
OnPropertyChanged("NodeCategory");
}
}

并像这样设置选定的项目-

NodeCategory = some_list_of_other_objects.Category.Name;

并像这样使用选定的值 -

Category selectedCategory = 
some_list_of_other_objects.FirstOrDefault(cat=> cat.Name == NodeCategory);

Category selectedCategory = 
Categories.FirstOrDefault(cat=> cat.Name == NodeCategory);

解决方案2-

另一种可能的解决方案是——

NodeCategory = 
Categories.FirstOrDefault(cat=> cat.Name == some_list_of_other_objects.Category.Name);

这样,您的 NodeCategory 属性将引用 Categories 集合中的对象,并且 SelectedItem 将起作用。

关于c# - WPF-MVVM-组合框选定项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11062297/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com