WPF TextBlock绑定不起作用

时间:2021-10-03 14:10:42

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

我尝试将TextBlock的Text属性绑定到我的属性,但文本不会更新。

XAML

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#

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 个解决方案

#1


11  

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

在MainWindow的构造函数中将MainWindow的DataContext设置为自身以解析绑定:

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

OR

要么

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

如果未设置DataContext,则必须使用RelativeSource从XAML显式解析绑定:

<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.

注 - 您始终可以检查Visual Studio的输出窗口是否存在任何绑定错误。

#1


11  

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

在MainWindow的构造函数中将MainWindow的DataContext设置为自身以解析绑定:

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

OR

要么

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

如果未设置DataContext,则必须使用RelativeSource从XAML显式解析绑定:

<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.

注 - 您始终可以检查Visual Studio的输出窗口是否存在任何绑定错误。