0
<Page x:Name="ChatPageName" x:Class="WindowsDesktop.Chat.ChatPage"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
      xmlns:local="clr-namespace:WindowsDesktop.Chat"
      mc:Ignorable="d" 
      d:DesignHeight="300" d:DesignWidth="300"
   Title="ChatPage">
<Grid>
    <ToolBar x:Name="ToBar" Grid.Row="0" HorizontalAlignment="Left" Margin="10,42,0,0" VerticalAlignment="Top" Height="28" Width="280">
        <TextBox x:Name="ToBarTextBox" Height="22.6666666666667" Margin="0" TextWrapping="Wrap" Text="{Binding Path=ToBarText, Source=ChatPageName}" VerticalAlignment="Top" Width="120"/>
        <Button x:Name="AddContactButton" Content="Add" Height="23" VerticalAlignment="Top" Width="75" Margin="0,0,0,-0.333" Click="AddContactButton_Click"/>
    </ToolBar>

I am trying to bind text on ToBarTextBox to a property called ToBarText on my class ChatPage. How would I do this?

Thanks.

James Nguyen
  • 91
  • 1
  • 3
  • 12

1 Answers1

0

Remove the Source property from xaml. Optionally, you can add FallbackValue

<TextBox x:Name="ToBarTextBox" Height="22.6666666666667" Margin="0" TextWrapping="Wrap" Text="{Binding Path=ToBarText, FallbackValue=ToBarText}" VerticalAlignment="Top" Width="120"/>

In the code behind, you need to set the DataContext (it is responsible for chosing the source of data for bindings). In your current setup, it looks like you're using a single class to handle the GUI and serving the data. In this case, use:

public ChatPage()
{
    // constructor code
    this.DataContext = this;
}

You also need to set the data source to implement INotifyPropertyChanged:

internal class ChatPage : INotifyPropertyChanged
{
    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;

    protected void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    #endregion

// ...

Having said that, I recommend learning about the Model-View-ViewModel pattern which helps separate the GUI code from the data source. Search for mvvm in wpf

Amadeusz Wieczorek
  • 3,139
  • 2
  • 28
  • 32