WPF将窗口的标题绑定到属性 [英] WPF bind title of window to property

查看:521
本文介绍了WPF将窗口的标题绑定到属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图绑定从Window派生的类(MainWindow)的属性(MyTitle)的值.我创建了一个名为MyTitleProperty的依赖项属性,实现了INotifyPropertyChanged接口,并修改了MyTitle的set方法以调用PropertyChanged事件,并将"MyTitle"作为属性名称参数传递.我在构造函数中将MyTitle设置为"Title",但是当窗口打开时,标题为空白.如果我在Loaded事件上设置了一个断点,则MyTitle ="Title",但是this.Title =".这肯定是我没有注意到的难以置信的明显现象.请帮忙!

I am trying to bind the value of a property (MyTitle) of a class (MainWindow) that derives from Window. I have created a dependency property called MyTitleProperty, implemented the INotifyPropertyChanged interface and modified the set method of MyTitle to call the PropertyChanged event, passing "MyTitle" as the property name parameters. I set MyTitle to "Title" in the constructor but when the window opens the title is blank. If I put a break point on the Loaded event then MyTitle = "Title" but this.Title = "". This is surely something unbelievably obvious that I've not noticed. Please help!

MainWindow.xaml

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:

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)
    {
    }
}

推荐答案

public MainWindow()
{
    InitializeComponent();

    DataContext = this;

    MyTitle = "Title";
}

那么您只需要在XAML中

Then you just need in the XAML

Title="{Binding MyTitle}"

然后,您不需要依赖项属性.

Then you don't need the dependency property.

这篇关于WPF将窗口的标题绑定到属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆