2013-07-19 62 views
0

我用this教程来构建一个自定义控件。现在,我想添加一条简单的消息(一个文本块)给用户控件,为用户提供一些指导。我想我可以添加一个公共属性,如本教程中的FileName,但是如何将textblock的Text属性连接到后面代码中的属性?然后确保文本块消息在属性更改时更新。如何将TextBlock设置为属性值?

我喜欢能够通过属性在代码中设置消息的想法,因为我可能会在页面上拥有多个此自定义控件类型的控件。我把它连接起来有点难。

谢谢!

+0

发布相关代码和XAML。 –

回答

1

这将是后面的代码,它实现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)); 
     } 
    }   
} 

这将是你的XAML结合的财产:

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

编辑:

新增的DataContext =这个;我通常不会绑定到背后的代码(我使用MVVM)。

+0

所有这些都应该在UserCOntrol中 –

相关问题