How do I set a TextBlock to a property value?

前端 未结 1 1881
滥情空心
滥情空心 2021-01-29 00:02

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 publ

相关标签:
1条回答
  • 2021-01-29 01:04

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

    0 讨论(0)
提交回复
热议问题