【问题标题】:How to connect SelectedIndex in Combobox to List Connection string?如何将组合框中的 SelectedIndex 连接到列表连接字符串?
【发布时间】:2021-10-25 06:25:33
【问题描述】:

如何将 Combobox 中的 SelectedIndex 连接到 List Connection 字符串?

这里是视图的实现:

XAML:

<ComboBox Name="cboxGDAservers" SelectionChanged="cboxGDAservers_SelectionChanged">
    <ComboBoxItem Content="GDA02"/> //If I select this I want it to connect to DKCDCVDCP30
    <ComboBoxItem Content="GDA03"/>
    <ComboBoxItem Content="GDA04"/>
</ComboBox>

背后的代码

private async void GDAworkers(object sender, EventArgs e)
{
  List<GDAWorkerDataModel> GDAWorkersConsolidated = new List<GDAWorkerDataModel>();
  string[] GDAServerList = new string[] { "DKCDCVDCP30", "DKCDCVDCP31", "DKCDCVDCP32" ...
     try
      {
       foreach (var GDAServer in GDAServerList)
         {
          List<GDAWorkerDataModel> GDAWorkers = new List<GDAWorkerDataModel>();
          var Result = GDAAcquisitionViewModel.GetWorkers(GDAServer);
          return Result;
          GDAWorkersConsolidated.AddRange(GDAWorkers);
         }
       }
       catch (Exception ex)
         {
           MessageBox.Show(ex.ToString());
         }
       DGGDAWorker.ItemsSource = GDAWorkersConsolidated;
      PbarGDAWorker.IsIndeterminate = false;
}

【问题讨论】:

  • 在 ComboBox 上设置 SelectedValuePath="Content" 并在您的 SelectionChanged 处理程序中查询 cboxGDAservers.SelectedValue
  • 当您提出问题时,请尝试正确表述。而且您显示的代码应该最少但可以工作。再说说如何理解“void”方法中的“return Result”?或者,在 XAML 中,您指定了 cboxGDAservers_SelectionChanged 方法,并且您正在显示 GDAworkers 的代码。 ComboxBox 被命名为“cboxGDAservers”,但在您的代码中没有引用该名称。

标签: c# wpf mvvm combobox connection


【解决方案1】:

您可以使用绑定到一个属性,而不是在使用所选项目的主方法中,您可以使用更改后的值:

Xaml

<ComboBox Name="cboxGDAservers"
          SelectedValuePath="Content"
          SelectedValue="{Binding Path=ConnectionString}">
<ComboBoxItem Content="GDA02"/> //If I select this I want it to connect to DKCDCVDCP30
<ComboBoxItem Content="GDA03"/>
<ComboBoxItem Content="GDA04"/>

并且在后面的代码中->你需要添加一个字符串属性的视图模型:

 public MyClass : INotifyPropertyChanged
 {
     private string _connectionString;
     public string ConnectionString
     {
        get { return _connectionString; }
        set
        {
            if (_connectionString== value) return;
            _connectionString= value;
            OnPropertyChanged("ConnectionString");
        }
     }
     // here you can use the workers with selected value from the added property

   }

【讨论】:

  • 你还需要展示视图模型是如何连接到视图的。
猜你喜欢
  • 1970-01-01
  • 2021-08-07
  • 2015-01-21
  • 1970-01-01
  • 2011-08-08
  • 2017-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多