Nodebay
Nodebay

Reputation: 554

Bind TextBlock Value to Object

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?

Upvotes: 0

Views: 672

Answers (2)

christoph
christoph

Reputation: 1051

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

Upvotes: 1

Eli Dagan
Eli Dagan

Reputation: 848

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

Upvotes: 1

Related Questions