lac*_*ohn 7 wpf binding window
我试图绑定从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>
Run Code Online (Sandbox Code Playgroud)
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)
{
}
}
Run Code Online (Sandbox Code Playgroud)
Scr*_*og1 23
public MainWindow()
{
InitializeComponent();
DataContext = this;
MyTitle = "Title";
}
Run Code Online (Sandbox Code Playgroud)
然后你只需要在XAML中
Title="{Binding MyTitle}"
Run Code Online (Sandbox Code Playgroud)
那你就不需要依赖属性了.
首先,INotifyPropertyChanged
如果你只想绑定一个,你就不需要了DependencyProperty
.这将是多余的.
您不需要设置DataContext
,也就是ViewModel场景.(只要有机会,请查看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));
Run Code Online (Sandbox Code Playgroud)
请注意UIPropertyMetadata
:它设置DP的默认值.
最后,在你的XAML中:
<Window ...
Title="{Binding MyTitle, RelativeSource={RelativeSource Mode=Self}}"
... />
Run Code Online (Sandbox Code Playgroud)
Title="{Binding Path=MyTitle, RelativeSource={RelativeSource Mode=Self}}"
Run Code Online (Sandbox Code Playgroud)