2012-03-07 99 views
4

我想绑定从Window派生的类(MainWindow)的属性(MyTitle)的值。我创建了一个名为MyTitleProperty的依赖项属性,实现了INotifyPropertyChanged接口并修改了MyTitle的set方法来调用PropertyChanged事件,并将“MyTitle”作为属性名称参数传递。我在构造函数中将MyTitle设置为“Title”,但当窗口打开时标题为空。如果我在Loaded事件上放置了一个断点,那么MyTitle =“Title”,但this.Title =“”。这肯定是我没有注意到的令人难以置信的显而易见的事情。请帮忙!WPF绑定属性窗口的标题

MainWindow.xaml

<Window 
    x:Class="WindowTitleBindingTest.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:this="clr-namespace:WindowTitleBindingTest" 
    Height="350" 
    Width="525" 
    Title="{Binding Path=MyTitle, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type this:MainWindow}}}" 
    Loaded="Window_Loaded"> 
    <Grid> 

    </Grid> 
</Window> 

MainWindow.xaml.cs:

public partial class MainWindow : Window, INotifyPropertyChanged 
{ 
    public static readonly DependencyProperty MyTitleProperty = DependencyProperty.Register("MyTitle", typeof(String), typeof(MainWindow)); 

    public String MyTitle 
    { 
     get { return (String)GetValue(MainWindow.MyTitleProperty); } 
     set 
     { 
      SetValue(MainWindow.MyTitleProperty, value); 
      OnPropertyChanged("MyTitle"); 
     } 
    } 

    public MainWindow() 
    { 
     InitializeComponent(); 

     MyTitle = "Title"; 
    } 

    public event PropertyChangedEventHandler PropertyChanged; 

    protected void OnPropertyChanged(String propertyName) 
    { 
     if (PropertyChanged != null) 
      PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 
    } 

    private void Window_Loaded(object sender, RoutedEventArgs e) 
    { 
    } 
} 
+3

哪里是你的DataContext被设置? – Khan 2012-03-07 15:01:58

+0

相对WPF新手。我之前完成了一些绑定,并且从来没有设置过它。我是否打算设置它?我会怎样设置它? – 2012-03-07 15:07:43

+1

所以我刚刚有了一个快速谷歌,似乎增加的DataContext =这一点;给我的构造函数解决我的问题。谢谢杰夫! – 2012-03-07 15:20:32

回答

20
public MainWindow() 
{ 
    InitializeComponent(); 

    DataContext = this; 

    MyTitle = "Title"; 
} 

然后你只需要在XAML

Title="{Binding MyTitle}" 

那么你不需要依赖项属性。

3
Title="{Binding Path=MyTitle, RelativeSource={RelativeSource Mode=Self}}" 
6

首先,你不需要INotifyPropertyChanged,如果你只是想绑定到DependencyProperty。那将是多余的。

你并不需要设置DataContext或者,那是一个视图模型场景。 (每当你有机会时都会查看MVVM模式)。现在

您的依赖项属性的声明是不正确,应该是:

public string MyTitle 
     { 
      get { return (string)GetValue(MyTitleProperty); } 
      set { SetValue(MyTitleProperty, value); } 
     } 

     // Using a DependencyProperty as the backing store for MyTitle. This enables animation, styling, binding, etc... 
     public static readonly DependencyProperty MyTitleProperty = 
      DependencyProperty.Register("MyTitle", typeof(string), typeof(MainWindow), new UIPropertyMetadata(null)); 

注意的UIPropertyMetadata:它为您的DP的默认值。

最后,在你的XAML:

<Window ... 
     Title="{Binding MyTitle, RelativeSource={RelativeSource Mode=Self}}" 
     ... />