我在MainWindow.xaml.cs中创建了自己的套接字类及其实例,我想创建一个小的TextBlock来监视连接状态。我一直在使用这个特定的链接:WPF textblock binding in XAML
这是代码尝试。 ComUplink.cs:
public class ComUplink
{
public String ConnectionStatus = "Idle";
public Socket Socklink;
}
在MainWindow.xaml.cs中:
public partial class MainWindow : Window
{
ComUpLink Uplink;
...
public void Login_Click(object Sender, RoutedEventArgs e)
{
Uplink = new ComUpLink();
}
}
AND在XAML文件中:
<TextBlock x:Name="textBlock3"
TextAlignment="Right"
HorizontalAlignment="Left"
Margin="12,218,0,0"
TextWrapping="Wrap"
Text="{Binding Path=Uplink.ConnectionString}"
VerticalAlignment="Top"
Foreground="#616161"
Width="236"/>
所以,我的问题是,为什么这种绑定不正确?我错过了INotifyPropertyChanged的实现吗?
答案 0 :(得分:1)
首先需要将文本块的数据上下文设置为主窗口或属性。 其次,您需要绑定到公共属性而不是字段
答案 1 :(得分:1)
你犯了三个小错误:
尝试这些修改:
MainWindow.xaml.cs中的:
public void Login_Click(object Sender, RoutedEventArgs e)
{
this.DataContext = new ComUpLink();
}
在ComUplink.cs中:
public class ComUplink : INotifyPropertyChanged
{
private String connectionStatus = "Idle";
public String ConnectionStatus
{
get
{
return this.connectionStatus;
}
set
{
this.connectionStatus = value;
this.OnPropertyChanged();
}
}
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
public Socket Socklink;
}
MainWindow.xaml中的:
<TextBlock x:Name="textBlock3"
TextAlignment="Right"
HorizontalAlignment="Left"
Margin="12,218,0,0"
TextWrapping="Wrap"
Text="{Binding Path=ConnectionStatus}"
VerticalAlignment="Top"
Foreground="#616161"
Width="236"/>