WPF绑定窗口标题到属性

13

我正在尝试绑定一个从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)
    {
    }
}

3
你的 DataContext 在哪里被设置了? - Khan
我是相对较新的WPF开发者。以前做过一些绑定,但从未设置过。我应该设置它吗?应该设置成什么? - lace.john
1
所以我刚刚快速搜索了一下,似乎在我的构造函数中添加DataContext = this;可以解决我的问题。感谢Jeff! - lace.john
3个回答

35
public MainWindow()
{
    InitializeComponent();

    DataContext = this;

    MyTitle = "Title";
}

那么你只需要在 XAML 中添加

Title="{Binding MyTitle}"

那么你就不需要依赖属性了。


8

首先,如果您只想绑定到 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}}"
       ... />

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接