簡體   English   中英

WPF TextBlock綁定不起作用

[英]WPF TextBlock Binding doesn't work

我嘗試將TextBlock Text屬性綁定到我的屬性,但文本不會更新。

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

在MainWindow的構造函數中將MainWindow的DataContext設置為自身以解析綁定:

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

要么

如果未設置DataContext,則必須使用RelativeSource從XAML顯式解析綁定:

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

- 您始終可以檢查Visual Studio的輸出窗口是否存在任何綁定錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM