我想綁定從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)
{
}
}
哪裏是你的DataContext被設置? – Khan 2012-03-07 15:01:58
相對WPF新手。我之前完成了一些綁定,並且從來沒有設置過它。我是否打算設置它?我會怎樣設置它? – 2012-03-07 15:07:43
所以我剛剛有了一個快速谷歌,似乎增加的DataContext =這一點;給我的構造函數解決我的問題。謝謝傑夫! – 2012-03-07 15:20:32