当前位置: 首页 > 知识库问答 >
问题:

WPF-MVVM-组合框选择项目

宰父阳焱
2023-03-14

我在后台有< code>ViewModel(实现< code > INotifyPropertyChanged )和类< code>Category,它只有一个< code>string类型的属性。我的ComboBox SelectedItem绑定到类别的实例。当我更改instance的值时,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;

要在组合框中选择该项,请使用相应的DisplayMemberPath

共有3个答案

华锦
2023-03-14

从我的小例子来看:

注意:这只是设置一个字符串(或另一个列表中的一个类别),但这里的基础应该是相同的:

基本上这是完成的:

private void button1_Click(object sender, RoutedEventArgs e)
{
    (this.DataContext as ComboBoxSampleViewModel).SelectCategory("Categorie 4");
}

这是我的XAML:

<Grid>
    <ComboBox Height="23" HorizontalAlignment="Left" Margin="76,59,0,0"   
              Name="comboBox1" VerticalAlignment="Top" Width="120" 
              ItemsSource="{Binding List.Categories}" 
              DisplayMemberPath="Name" 
              SelectedValue="{Binding NodeCategory, Mode=TwoWay}" />
    <Button Content="Button" Height="27" HorizontalAlignment="Left" 
            Margin="76,110,0,0" Name="button1" VerticalAlignment="Top" 
            Width="120" Click="button1_Click" />
</Grid>

并且在窗口的视图模式中

class ComboBoxSampleViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged(string info)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(info));
        }
    }

    public CategoryList List { get; set; }

    public ComboBoxSampleViewModel()
    {
        this.List = new CategoryList();
        NodeCategory = List.Selected;
    }

    private ComboBoxSampleItemViewModel nodeCategory;
    public ComboBoxSampleItemViewModel NodeCategory
    {
        get
        {
            return nodeCategory;
        }
        set
        {
            nodeCategory = value;
            NotifyPropertyChanged("NodeCategory");
        }
    }

    internal void SelectCategory(string p)
    {
        this.List.SelectByName(p);
        this.NodeCategory = this.List.Selected;
    }
}

在这个小班级的帮助下:

public class CategoryList
{
    public ObservableCollection<ComboBoxSampleItemViewModel> Categories { get; set; }
    public ComboBoxSampleItemViewModel Selected { get; set; }
    public CategoryList()
    {
        Categories = new ObservableCollection<ComboBoxSampleItemViewModel>();

        var cat1 = new ComboBoxSampleItemViewModel() { Name = "Categorie 1" };
        var cat2 = new ComboBoxSampleItemViewModel() { Name = "Categorie 2" };
        var cat3 = new ComboBoxSampleItemViewModel() { Name = "Categorie 3" };
        var cat4 = new ComboBoxSampleItemViewModel() { Name = "Categorie 4" };

        Categories.Add(cat1);
        Categories.Add(cat2);
        Categories.Add(cat3);
        Categories.Add(cat4);

        this.Selected = cat3;
    }

    internal void SelectByName(string p)
    {
        this.Selected = this.Categories.Where(s => s.Name.Equals(p)).FirstOrDefault();
    }
}

和这个项目视图模型

public class ComboBoxSampleItemViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged(string info)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(info));
        }
    }

    private string name;

    public string Name 
    { 
        get
        {
            return name;
        }
        set
        {
            name = value;
            NotifyPropertyChanged("Name");
        }
    }
}
养淇
2023-03-14

您的XAML需要一些修改,但我认为真正的问题在于您发布的代码,我认为这些代码没有讲述完整的故事。对于初学者来说,您的组合框ItemSource绑定到一个名为类别的属性,但您没有显示该属性是如何编码的,也没有显示您的节点类别属性最初是如何与该项目同步的。

尝试使用以下代码,您将看到当用户更改组合框中的值时,所选项目保持同步。

XAML

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<StackPanel>
    <ComboBox x:Name="categoryComboBox"
              Grid.Column="1"
              Grid.Row="3"
              Grid.ColumnSpan="2"
              Margin="10"
              ItemsSource="{Binding Categories}"
              DisplayMemberPath="Name"
              SelectedItem="{Binding NodeCategory}" />
    <Label Content="{Binding NodeCategory.Name}" />
</StackPanel>

代码隐藏

public partial class MainWindow : Window, INotifyPropertyChanged
{
    private ObservableCollection<Category> _categories = new ObservableCollection<Category>
    {
        new Category { Name = "Squares"},
        new Category { Name = "Triangles"},
        new Category { Name = "Circles"},
    };

    public MainWindow()
    {
        InitializeComponent();
        NodeCategory = _categories.First();
        this.DataContext = this;
    }

    public IEnumerable<Category> Categories
    {
        get { return _categories; }
    }

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

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

    public event PropertyChangedEventHandler PropertyChanged;
}

[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;
}
阴高刚
2023-03-14

你在这行设定的类别-

NodeCategory = some_list_of_other_objects.Category;

并且您的类别集合中存在的一个(ItemsSource=“{绑定类别}”)应该引用相同的对象。如果不是,则“选定项”将不起作用。

您也可以像这样尝试使用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);

另一个可能的解决方案可以是-

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

这样,您的节点类别属性将引用类别集合中的对象,并且选择项目将起作用。

 类似资料:
  • 我有一个列表类型的组合框。我通过datacontext绑定了ItemsSource和ItemSelected。如果所选项目已经更改,我会显示一条弹出消息,确认用户的操作。单击“确定”后,选择会发生变化。但是在点击“取消”时,选择应该被取消,而先前的项目应该被保留。下面是绑定到combobox的SelectedItem的属性。 组合框在弹出窗口中。那么Dispatcher对象在这种情况下能工作吗?

  • 日安, 我希望我的组合框选择其中的第一个项目。我正在使用C#和WPF。我从DataSet读取数据。要填充组合框: 组合框XAML代码: 如果我尝试: 它不起作用。

  • 我有一个ComboBox,我想在视图模型中将选中的项目文本绑定到一个字符串。 现在我有了: Xaml: 视图模型: 当我运行该程序时,我收到异常: Binding表达式路径错误:在“对象”上找不到“类型”属性“观察集合'1'(HashCode=34166919)”。Binding表达式:路径=类型;数据项=“观察集合'1'(HashCode=34166919);目标元素是“组合框”(名称=");目

  • 问题内容: 我们正在使用Selenium WebDriver和JBehave在我们的Web应用程序上运行“集成”测试。我有一种方法,可以在表单输入中输入一个值。 但是,当我尝试使用它在下拉列表中选择一个项目时,它(毫无疑问)失败了 java.lang.UnsupportedOperationException:您只能设置作为输入元素的元素的值 如何在组合中选择一个值? 问题答案: 这是怎么做的:

  • 使用Datagridtemplatecolumn将WPFDatagrid绑定到组合框。很难获得组合框绑定的selectedItem。我发现了类似的例子,但这并不能解决我的问题。 请在下面找到我的 XAML 的代码片段和数据结构: 我在上面定义了一个数据结构,它实现了INotifyPropertychanged接口。 现在,在视图模型中,有一个可观察的X列表集合,即XList,它绑定到XAML中的数

  • 所以,我有一个奇怪的问题,我从组合框列表中选择一个项目,为了填充第二个组合框,我必须首先从第一个组合框中再次选择单词,而不是从项目列表中,而是单词本身。只有这样,代码才会注册我选择了该项目。我拥有的代码是简单的$variable.SelectedItem。参见下面的代码; 我想做的就是从下拉列表中选择位置“医院”,然后第二个名为“$ComboBox_Printer”的组合框填充我服务器中的打印机名