0

I've created my own socket class and an instance of it in MainWindow.xaml.cs, and I want to create a small little TextBlock to monitor the connection status. I've been using this specific link: WPF textblock binding in XAML

Here's the code attempt. ComUplink.cs:

 public class ComUplink { public String ConnectionStatus = "Idle"; public Socket Socklink; } 

In MainWindow.xaml.cs:

 public partial class MainWindow : Window { ComUpLink Uplink; ... public void Login_Click(object Sender, RoutedEventArgs e) { Uplink = new ComUpLink(); } } 

AND in the XAML file:

<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"/> 

So, my question is, why isn't this binding properly? Am I missing an implementation of INotifyPropertyChanged?

2 Answers 2

1

Well you made three little mistakes:

  1. You can only bind to properties (if those values change use INotifyPropertyChanged)
  2. You need to set the DataContext
  3. Your Binding used the wrong property name (ConnectionString instead of ConnectionStatus)

Try those modifications:

in MainWindow.xaml.cs:

public void Login_Click(object Sender, RoutedEventArgs e) { this.DataContext = new ComUpLink(); } 

in 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; } 

in 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"/> 
Sign up to request clarification or add additional context in comments.

4 Comments

This is a lot of work and structure change for one feature. Thanks, though.
Did it work for you? You should get used to it while WPF is based upon this concepts.
Yes! And what do you mean by while? Is it subject to change soon?
Sorry, "because" would have been the better choice. Those concepts will not change.
1

You first need to set the data context of the text block to be the main window or a property. Second you need to bind to a public property not to field

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.