单击 Caliburn.Micro 中的按钮将项目添加到 ComboBox

Button click in Caliburn.Micro adds items to ComboBox

我刚开始使用 MahApps.Metro 和 Caliburn.Micro 在 C# 中编写我的简单应用程序,但我遇到了问题。我对 MVVM 模型不是很熟悉,所以我想了解它。我想要做的是在单击按钮后用项目填充 ComboBox(单击按钮搜索 COM 端口并将 COM 添加到组合框)。你能告诉我怎么做吗?这是我的一部分 MainView.xaml:

<WrapPanel Orientation="Horizontal">
                    <WrapPanel Orientation="Vertical">
                        <Label Name="SelectCOM" Content="{x:Static r:Translations.SelectCOM}" FontWeight="Bold" FontSize="12" />
                        <ComboBox Width="235" 
                                  x:Name="COMPorts" 
                                  SelectedItem="{Binding SelectedPort}" />
                    </WrapPanel>
                    <Button Margin="10,0,0,0" 
                            Width="70" 
                            Content="{x:Static r:Translations.Refresh}" 
                            HorizontalAlignment="Right" 
                            cal:Message.Attach="RefreshCOM" />
                </WrapPanel>

这是我的 MainViewModel:

public class MainViewModel : PropertyChangedBase
    {
        IDevice Device = null;
        private string selectedPort;

        public void RefreshCOM()
        {
            string[] ports = SerialPort.GetPortNames();


        }

        public string SelectedPort
        {
            get
            {
                return this.selectedPort;
            }

            set
            {
                this.selectedPort = value;
                this.NotifyOfPropertyChange(() => this.SelectedPort);
            }
        }
    }

你需要"bind" the list of COM ports to the control's ItemsSource.

<ComboBox Width="235" 
          x:Name="COMPorts" 
          SelectedItem="{Binding SelectedPort}"
          ItemsSource="{Binding ComPorts}" />

并且不要忘记更新您的视图模型(添加 observable collection com 端口名称)

public class MainViewModel : PropertyChangedBase
{
    // ...
    public MainViewModel() 
    {
      ComPorts = new ObservableCollection<string>();
    }
    public void RefreshCOM()
    {
        string[] ports = SerialPort.GetPortNames();
        foreach(var port in ports)
        {
           ComPorts.Add(port);
        }
    }

    public ObservableCollection<string> ComPorts {get; private set;}
    // ...
}