How do I set a TextBlock to a property value?

2020-05-03 00:59发布

问题:

I used this tutorial to build a custom control. Now, I'd like to add a simple message (a textblock) to the user control to give the user some guidance. I think I can add a public property, like FileName in the tutorial, but how do I wire up the textblock's Text property to the property in the code behind? And then make sure the textblock message updates if the property changes.

I like the idea of being able to set the message in code, via a property, because I will likely have multiple controls of this custom control type on a page. I'm just a bit stumped on wiring it up.

Thanks!

回答1:

This would be your code behind, which implements INotifyPropertyChanged:

/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window, INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private string _fileName;

    /// <summary>
    /// Get/Set the FileName property. Raises property changed event.
    /// </summary>
    public string FileName
    {
        get { return _fileName; }
        set
        {
            if (_fileName != value)
            {
                _fileName = value;

                RaisePropertyChanged("FileName");
            }
        }
    }

    public MainWindow()
    {
        DataContext = this;
        FileName = "Testing.txt";
    }

    private void RaisePropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }         
}

This would be your XAML that binds to the property:

<TextBlock Text="{Binding FileName}" />

EDIT:

Added DataContext = this; i don't normally bind to the code behind (I use MVVM).