If the you need to update the binding, the property Joke must be a DependencyProperty or the Windows must implement INotifyPropertyChanged interface.
On the view, the binding needs to know Source.
Example #1 (Using DependencyProperty):
public partial class JokesMessageBox : Window { public JokesMessageBox() { InitializeComponent(); ReadFile(Path); //example call } public string Joke { get { return (string)GetValue(JokeProperty); } set { SetValue(JokeProperty, value); } } public static readonly DependencyProperty JokeProperty = DependencyProperty.Register("Joke", typeof(string), typeof(JokesMessageBox), new PropertyMetadata(null)); public const string Path = "data/jokes.txt"; public void ReadFile(string path) { Joke = File.ReadAllText(path); } }
Example #2 (Using INotifyPropertyChanged interface):
public partial class JokesMessageBox : Window, INotifyPropertyChanged { public JokesMessageBox() { InitializeComponent(); ReadFile(Path); //example call } private string _joke; public string Joke { get { return _joke; } set { if (string.Equals(value, _joke)) return; _joke = value; OnPropertyChanged("Joke"); } } public const string Path = "data/jokes.txt"; public void ReadFile(string path) { Joke = File.ReadAllText(path); } //INotifyPropertyChanged members public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged(string propertyName) { var handler = PropertyChanged; if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); } }
And the view (XAML partial):
... <TextBlock HorizontalAlignment="Left" Margin="22,10,0,0" TextWrapping="Wrap" Text="{Binding Joke,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=Window}}" VerticalAlignment="Top" Height="60" Width="309"/> ...
I hope it helps.
ReadFilecalled?DataBinding.