You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将WPF ComboBox选中项与My.Settings绑定并预设选中?

串口保存与启动预设选中解决方案

一、修正ViewModel初始化逻辑

程序启动时读取已保存的串口,自动设置选中项:

Public Sub New()
    ' 先获取当前可用串口列表
    _comports = System.IO.Ports.SerialPort.GetPortNames()
    ' 读取上次保存的串口
    Dim savedPort = My.Settings.comport
    
    ' 校验保存的串口是否当前可用,避免无效选中
    If _comports.Contains(savedPort) Then
        _myserialportx = savedPort
    Else
        ' 可选逻辑:若保存的串口不可用,默认选中第一个可用串口或置空
        If _comports.Length > 0 Then
            _myserialportx = _comports(0)
            My.Settings.comport = _myserialportx ' 更新设置为当前有效串口
        Else
            _myserialportx = String.Empty
        End If
    End If
    
    ' 通知UI属性变更
    SetAndNotify(NameOf(myserialportx), _myserialportx, _myserialportx)
    SetAndNotify(NameOf(ComPorts), _comports, _comports)
End Sub

二、优化ComPorts属性实现

原属性每次Get都重新获取串口列表,改为字段存储,添加主动刷新方法:

Private _comports As String()
Public Property ComPorts() As String()
    Get
        Return _comports
    End Get
    Set(ByVal value As String())
        _comports = value
        SetAndNotify(NameOf(ComPorts), _comports, value)
    End Set
End Property

' 刷新串口列表的方法,可在启动或手动触发(如按钮点击)时调用
Public Sub RefreshComPorts()
    Dim newPorts = System.IO.Ports.SerialPort.GetPortNames()
    ' 仅当列表变化时更新,避免不必要的UI刷新
    If Not newPorts.SequenceEqual(_comports) Then
        _comports = newPorts
        SetAndNotify(NameOf(ComPorts), _comports, newPorts)
        
        ' 若原选中串口已不存在,自动切换到第一个可用串口
        If Not _comports.Contains(_myserialportx) AndAlso _comports.Length > 0 Then
            myserialportx = _comports(0)
        End If
    End If
End Sub

三、修正ComboBox绑定配置

原绑定的SelectedValuePath无效(因ItemsSource是字符串数组),改为绑定SelectedItem,并调整绑定模式:

<ComboBox Grid.Row="7" Grid.Column="2" 
          IsSynchronizedWithCurrentItem="True" 
          ItemsSource="{Binding ComPorts, Mode=OneWay}" 
          SelectedItem="{Binding myserialportx, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
  • ItemsSource设为OneWay:串口列表仅需从VM单向同步到UI,无需反向更新
  • SelectedItem绑定myserialportx:直接将选中的字符串赋值给属性,逻辑更直观

四、确保设置持久化

在程序关闭时调用保存方法,保证选中的串口写入配置文件:

Private Sub MainWindow_Closing(sender As Object, e As CancelEventArgs) Handles Me.Closing
    My.Settings.Save()
End Sub

内容的提问来源于stack exchange,提问作者user18107302

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 11:53:16