Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/281.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何以编程方式设置数据绑定WPF组合框的SelectedItem?_C#_Wpf_Data Binding_Combobox - Fatal编程技术网

C# 如何以编程方式设置数据绑定WPF组合框的SelectedItem?

C# 如何以编程方式设置数据绑定WPF组合框的SelectedItem?,c#,wpf,data-binding,combobox,C#,Wpf,Data Binding,Combobox,问题:任何人都可以提供一个完整的代码示例,说明如何在不使用MyComboBox.SelectedIndex的情况下通过编程更改数据绑定WPF组合框的SelectedItem 代码示例:这是我目前拥有的 XAML: 代码隐藏: using System.Collections.ObjectModel; using System.Windows; namespace Wpf.ComboBoxDemo { public partial class MainWindow : Window

问题:任何人都可以提供一个完整的代码示例,说明如何在不使用MyComboBox.SelectedIndex的情况下通过编程更改数据绑定WPF组合框的SelectedItem

代码示例:这是我目前拥有的

XAML:


代码隐藏:

using System.Collections.ObjectModel;
using System.Windows;

namespace Wpf.ComboBoxDemo
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            ObservableCollection<Person> myPersonList = new ObservableCollection<Person>();

            Person personJobs = new Person("Steve", "Jobs");
            Person personGates = new Person("Bill", "Gates");

            myPersonList.Add(personJobs);
            myPersonList.Add(personGates);

            MyComboBox.ItemsSource = myPersonList;

            // How do I programmatically select the second Person, i.e. "Gates"?
            // The best pratice must be to somehow to set something like IsCurrentlySelected on the model, so the view update automatically. But how?
            MyComboBox.SelectedIndex = 1; // This works, but is there no way without using the index?

        }

        private class Person
        {
            public string FirstName { get; set; }
            public string LastName { get; set; }

            public Person(string firstName, string lastName)
            {
                FirstName = firstName;
                LastName = lastName;
            }
        }
    }
}
使用System.Collections.ObjectModel;
使用System.Windows;
名称空间Wpf.ComboxDemo
{
公共部分类主窗口:窗口
{
公共主窗口()
{
初始化组件();
ObservableCollection myPersonList=新的ObservableCollection();
Person personJobs=新人(“史蒂夫”、“乔布斯”);
Person personGates=新人(“比尔”、“盖茨”);
myPersonList.Add(personJobs);
myPersonList.Add(personGates);
MyComboBox.ItemsSource=myPersonList;
//如何以编程方式选择第二个人,即“盖茨”?
//最好的做法必须是以某种方式在模型上设置类似IsCurrentlySelected的内容,以便视图自动更新。但是如何设置呢?
MyComboBox.SelectedIndex=1;//这是可行的,但是如果不使用索引,就没有办法了吗?
}
私人阶级人士
{
公共字符串名{get;set;}
公共字符串LastName{get;set;}
公众人物(字符串名、字符串名)
{
名字=名字;
LastName=LastName;
}
}
}
}
类似的问题:我当然先在互联网上搜索过,但没有找到对我有帮助的东西

  • 在ViewModel()内更改枚举绑定组合框的SelectedItem
  • 在WPF(3.5sp1)()中以编程方式设置组合框SelectedItem
    • 在我的头顶(我可能错了),使窗口实现并添加事件:

      namespace Wpf.ComboBoxDemo
      {
          public partial class MainWindow : Window, INotifyPropertyChanged
          {
              public event PropertyChangedEventHandler PropertyChanged;
      
              public MainWindow()
              {
      
      然后为当前选定的项目添加一个属性,该属性在发生更改时发出通知:

              private Person _selected;
              public Person MySelected
              {
                  get { return _selected; }
                  set
                  {
                      if (value != _selected)
                      {
                          _selected = value;            
                          if (PropertyChanged != null)
                          {
                              PropertyChanged(this,
                                  new PropertyChangedEventArgs("MySelected"));
                          }
                      }
                  }
              }
      
      现在绑定组合框(这里的绑定可能更高级,但有时为了保持简单,我将datacontext放在代码中):

      XAML

              <ComboBox
                  Name="MyComboBox"
                  DisplayMemberPath="LastName"
                  SelectedItem="{Binding MySelected}" />
      
          public MainWindow()
          {
              InitializeComponent();
              // ...
      
              // this will cause the "MySelected" binding to target the correct property on this object
              MyComboBox.DataContext = this;
          }
      
      我想是这样的。我现在不能测试它,但希望它能把你推向正确的方向

      编辑:如果您想尝试“其他方式”的绑定,请参见下文。展开
      SelectedItem
      绑定,如下所示:

              <ComboBox
                  Name="MyComboBox"
                  DisplayMemberPath="LastName"
                  SelectedItem="{Binding MySelected,
                      RelativeSource={RelativeSource FindAncestor,
                          AncestorType={x:Type Window}}}" />
      
      这是因为
      FindAncestor
      模式使
      组合框
      本身找到它应该绑定到的属性的对象,而不是您专门声明的对象

      目前办公室里的热门话题是这两种方式中哪一种是最好的。对我来说,更多的是XAML,更少的代码落后(或者反过来说),只需使用将代码放在您可以轻松工作的地方的方法即可。我认为在某些情况下,后者是首选的(比如在其他控件中包含数据绑定控件),但我只是涉猎了一下,所以我还没有真正弄清楚这些部分

      在我的脑海中(我可能错了),实现窗口并添加事件:

      namespace Wpf.ComboBoxDemo
      {
          public partial class MainWindow : Window, INotifyPropertyChanged
          {
              public event PropertyChangedEventHandler PropertyChanged;
      
              public MainWindow()
              {
      
      然后为当前选定的项目添加一个属性,该属性在发生更改时发出通知:

              private Person _selected;
              public Person MySelected
              {
                  get { return _selected; }
                  set
                  {
                      if (value != _selected)
                      {
                          _selected = value;            
                          if (PropertyChanged != null)
                          {
                              PropertyChanged(this,
                                  new PropertyChangedEventArgs("MySelected"));
                          }
                      }
                  }
              }
      
      现在绑定组合框(这里的绑定可能更高级,但有时为了保持简单,我将datacontext放在代码中):

      XAML

              <ComboBox
                  Name="MyComboBox"
                  DisplayMemberPath="LastName"
                  SelectedItem="{Binding MySelected}" />
      
          public MainWindow()
          {
              InitializeComponent();
              // ...
      
              // this will cause the "MySelected" binding to target the correct property on this object
              MyComboBox.DataContext = this;
          }
      
      我想是这样的。我现在不能测试它,但希望它能把你推向正确的方向

      编辑:如果您想尝试“其他方式”的绑定,请参见下文。展开
      SelectedItem
      绑定,如下所示:

              <ComboBox
                  Name="MyComboBox"
                  DisplayMemberPath="LastName"
                  SelectedItem="{Binding MySelected,
                      RelativeSource={RelativeSource FindAncestor,
                          AncestorType={x:Type Window}}}" />
      
      这是因为
      FindAncestor
      模式使
      组合框
      本身找到它应该绑定到的属性的对象,而不是您专门声明的对象


      目前办公室里的热门话题是这两种方式中哪一种是最好的。对我来说,更多的是XAML,更少的代码落后(或者反过来说),只需使用将代码放在您可以轻松工作的地方的方法即可。我认为在某些情况下,后者是首选的(比如在其他控件中包含数据绑定控件),但我只是涉猎了一下,所以我还没有真正弄清楚这些部分

      很高兴我能帮忙。:)如果你想试试的话,我添加了第二种绑定方法。这段代码也没有经过测试,所以我希望我还剩下一些运气。现在我在这个.DataContext=myPersonlist(它不需要组合框来命名)和你的FindAncestor方法之间左右为难。很高兴我能帮上忙。:)如果你想试试的话,我添加了第二种绑定方法。这段代码也没有经过测试,所以我希望我还剩下一些运气。现在我在这个.DataContext=myPersonlist(它不需要组合框来命名)和FindAncestor方法之间左右为难,后者根本不需要代码。