【发布时间】:2012-03-07 14:59:07
【问题描述】:
我正在尝试绑定派生自 Window 的类 (MainWindow) 的属性 (MyTitle) 的值。我创建了一个名为 MyTitleProperty 的依赖属性,实现了 INotifyPropertyChanged 接口并修改了 MyTitle 的 set 方法以调用 PropertyChanged 事件,将“MyTitle”作为属性名称参数传递。我在构造函数中将 MyTitle 设置为“Title”,但是当窗口打开时,标题为空白。如果我在 Loaded 事件上设置一个断点,那么 MyTitle = "Title" 但 this.Title = ""。这肯定是令人难以置信的显而易见的事情,我没有注意到。请帮忙!
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 是在哪里设置的?
-
相对 WPF 新手。我以前做过一些绑定,从来没有设置过。我应该设置它吗?我会把它设置成什么?
-
所以我刚刚快速搜索了一下,似乎添加了 DataContext = this;我的构造函数解决了我的问题。谢谢杰夫!