Привязка текстового блока WPF не работает

#c# #wpf #xaml #binding #textblock

#c# #wpf #xaml #привязка #текстовый блок

Вопрос:

Я пытаюсь привязать Text свойство TextBlock к моему свойству, но текст не обновляется.

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

Комментарии:

1. где вы устанавливаете datacontext?

2. @Sajeetharan Я думаю, что htis настраивается d:DataContext="{d:DesignData MainWindow}

Ответ №1:

Установите DataContext MainWindow для самого себя в конструкторе MainWindow для разрешения привязки:

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

или

Если вы не задаете DataContext, вам придется явно разрешить привязку из XAML с помощью RelativeSource :

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

ПримечаниеВы всегда можете пойти и проверить окно вывода Visual Studio на наличие ошибок привязки.