I am trying to bind a property value (MyTitle) of a class (MainWindow) that comes from a window. I created the MyTitleProperty dependency property, implemented the INotifyPropertyChanged interface, and modified the set MyTitle method to raise the PropertyChanged event by passing "MyTitle" as the property name parameters. I set MyTitle to "Title" in the constructor, but when the window opens, the title will be empty. If I set a breakpoint on the Loaded event, then Mytitle = "Title", but this.title = "". This, of course, is something incredibly obvious that I did not notice. Please, help!
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) { } }
source share