2014-07-04 14 views
6

Ich versuche Bind Text Eigenschaft von TextBlock zu meinem Eigentum, aber Text aktualisiert nicht.WPF TextBlock Binding

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

Wo setzen Sie den Datenkontext? – Sajeetharan

+0

@Sajeetharan I Thint htis setzt 'd: DataContext = "{d: DesignData MainWindow}' –

Antwort

8

Set DataContext von Mainwindow sich im Konstruktor von Mainwindow zu lösen Bindung:

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

OR

Wenn Sie nicht über Datacontext festgelegt, müssen Sie lösen hiermit ausdrücklich von XAML Bindung mit RelativeSource:

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

Hinweis-Sie können immer Ausgang gehen und überprüfen Fenster von Visual Studio für Bindungsfehler.

+1

Danke, ich habe den zweiten Weg verwendet und es funktioniert. –