WPF(XAML+VB)图片切换式连接按钮点击无响应问题排查
问题分析与修复方案
核心问题1:图片引用比较完全不成立
你在connection()函数里用Object.ReferenceEquals(lb_con.Source, My.Resources.power_on)判断状态,这逻辑永远不会触发:
- XAML初始化时,
Source="Resources/power-on.png"会生成一个BitmapImage实例 My.Resources.power_on是项目资源中的另一类图像对象(比如Bitmap),和XAML创建的实例不是同一个引用- 后续代码里
New BitmapImage(New Uri(...))又会生成全新实例,导致两次引用永远不相等,连接/断开的分支逻辑都不会执行,看起来就是点击无反应
核心问题2:Uri路径类型错误
用UriKind.Absolute加载项目内资源会把路径当成绝对路径,而本地项目资源应该用相对路径或Pack URI,否则可能出现图片加载失败的问题。
修复方案
1. 用独立变量记录连接状态
不要依赖图片Source判断状态,新增布尔变量存储当前连接状态:
Private IsConnected As Boolean = False ' 初始为断开状态
2. 修改connection()函数的判断逻辑
把基于图片引用的判断替换为基于状态变量的判断,同时修正图片加载路径:
Private Sub connection() If tb_server.Text = String.Empty Or tb_username.Text = String.Empty Or tb_psdd.Text = String.Empty Then MsgBox("All fields are required", MsgBoxStyle.Exclamation, "Empty Fields") Exit Sub End If intDisconnected = False If Not IsConnected Then ' 当前为断开状态,执行连接逻辑 If CheckInternetConnection() = True Then Try ' ... 你的连接逻辑 ... rashandler = rasdialer.DialAsync() ' 切换为断开状态图片(使用相对路径) lb_con.Source = New BitmapImage(New Uri("Resources/power-off.png", UriKind.Relative)) IsConnected = True ' 更新状态为已连接 Catch exc As Exception MsgBox(exc.Message, MsgBoxStyle.Critical, "Connection Error") End Try Else MsgBox("Either your internet Or server (http://www.google.com) used to check internet connectivity is down.", MsgBoxStyle.Critical, "Connection Error") End If Else ' 当前为已连接状态,执行断开逻辑 intDisconnected = True If rasdialer.IsBusy Then rasdialer.DialAsyncCancel() Else Dim con As RasConnection = RasConnection.GetActiveConnectionByHandle(rashandler) If con IsNot Nothing Then con.HangUp() End If End If ' 切换为连接状态图片(使用相对路径) lb_con.Source = New BitmapImage(New Uri("Resources/power-on.png", UriKind.Relative)) IsConnected = False ' 更新状态为断开 End If End Sub
3. 可选:用Button包裹Image优化交互
Image控件的点击交互不如Button稳定,建议用透明Button包裹Image,更符合WPF交互逻辑:
<Button x:Name="btn_con" HorizontalAlignment="Center" Margin="0,74,0,0" VerticalAlignment="Top" Background="Transparent" BorderThickness="0" Cursor="Hand"> <Image x:Name="img_con" Source="Resources/power-on.png"/> </Button>
然后把事件改为btn_con_Click:
Private Sub btn_con_Click(sender As Object, e As RoutedEventArgs) Handles btn_con.Click connection() End Sub
内容的提问来源于stack exchange,提问作者rurjaf
相关产品推荐
相关产品推荐

