WPF将窗口标题绑定到属性

sqxo8psd  于 2023-01-10  发布在  其他
关注(0)|答案(3)|浏览(236)

我正在尝试绑定属性的值类的(我的标题)我创建了一个名为MyTitleProperty的依赖属性,实现了INotifyPropertyChanged接口,并修改了MyTitle的set方法以调用PropertyChanged事件,传递“MyTitle”作为属性名参数。我在构造函数中将MyTitle设置为“Title”,但是当窗口打开时,标题是空的。如果我在Loaded事件上设置一个断点,那么MyTitle =“Title”,但是这个.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)
    {
    }
}
ffscu2ro

ffscu2ro1#

public MainWindow()
{
    InitializeComponent();

    DataContext = this;

    MyTitle = "Title";
}

那么您只需要在XAML中

Title="{Binding MyTitle}"

那么就不需要dependency属性了。

pprl5pva

pprl5pva2#

首先,如果只想绑定到DependencyProperty,就不需要INotifyPropertyChanged
您也不需要设置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));

请注意UIPropertyMetadata:它设置DP的默认值。
最后,在XAML中:

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

wpx232ag3#

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

相关问题