WPF TextBlock Binding doesn't work
Asked Answered
L

1

12

I try bind Text property of TextBlock to my property but text does not update.

XAML

<Window x:Name="window" x:Class="Press.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"
    Title="Press analyzer" Height="350" Width="525" ContentRendered="Window_ContentRendered"
    d:DataContext="{d:DesignData MainWindow}">
...
    <StatusBar Name="StatusBar" Grid.Row="2" >
        <TextBlock Name="StatusBarLabel" Text="{Binding Message}"/>
    </StatusBar>
</Window>

C#

public partial class MainWindow : Window, INotifyPropertyChanged 
{
    private string _message;
    public string Message
    {
        private set
        {
            _message = value;
            OnPropertyChanged("Message");
        }
        get
        {
            return _message;
        }
    }
public event PropertyChangedEventHandler PropertyChanged;

    [NotifyPropertyChangedInvocator]
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }
}
Litha answered 4/7, 2014 at 10:18 Comment(2)
where are you setting the datacontext?Dorene
@Dorene I thint htis is setting d:DataContext="{d:DesignData MainWindow}Litha
F
18

Set DataContext of MainWindow to itself in constructor of MainWindow to resolve binding:

public MainWindow()
{
   InitializeComponent();
   this.DataContext = this;
}

OR

If you don't set DataContext, you have to resolve binding explicitly from XAML using RelativeSource:

<TextBlock Name="StatusBarLabel"
           Text="{Binding Message, RelativeSource={RelativeSource 
                                   Mode=FindAncestor, AncestorType=Window}}"/>

Note - You can always go and check output window of Visual Studio for any binding errors.

Foch answered 4/7, 2014 at 10:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.