基于信息类的 WPF 窗口标题绑定



我有Wpf-App来处理人对象。Person Struct是Sql服务器表,我在项目中使用Linq-to-Sql(所以dbml中有类引用person)。

我有更新或插入人员的表格(简单的模态窗口)。在这个窗口中,我有Peoperty具有当前人员值。

public Person CurrentPerson { get; set; }

所以我寻找的是:

如何绑定此窗口的标题基于CurrentPerson.FullName?如果CurrentPerson.FullName更改,则绝对必须更改窗口标题!

编辑:更多信息
我想根据CurrentPerson.Name设置与CurrentPerson.Name相同来更改窗口标题。所以这可能会改变一些东西。我也搜索了之前找到这个和这个关于更改部分标题的问题。但我需要根据价值更改标题的某些部分。

首先,您的代码隐藏或视图模型应该实现INotifyPropertyChanged。之后,实现如下所示的属性WindowTitle

public string WindowTitle 
{ 
    get { return "Some custom prefix" + CurrentPerson.FullName; } 
}

在此之后,每当您更改CurrentPerson上的FullName时,只需抛出一个PropertyChanged事件,例如:

Person _currentPerson;
public Person CurrentPerson 
{
    get { return _currentPerson; }
    set
    {
        _currentPerson = value;
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs("WindowTitle"));
    }
}

编辑:请发布您的xaml代码以进行绑定,看看您对新手帖子的评论,似乎是罪魁祸首。此外,请检查是否将WindowDataContext设置为自身。

编辑:删除了旧答案,因为我完全误解了这个问题。

问题可能出在您的绑定中。我认为绑定失败是因为它无法决定在哪里搜索CurrentUser(binding source).你能试试这个吗——

编辑 2:可以命名控件,然后在绑定元素中使用该名称,如下所示:

<Window x:Class="TestApp.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="{Binding ElementName=MW,Path=CurrentUser.FullName, StringFormat='Welcome {0}!'}"        
    Name="MW">

如果这不起作用,可以通过转到以下位置为绑定表达式启用 WPF 调试:

Tools -> Options -> Debugging -> Output Window -> WPF Trace Settings [这是针对VS2010的;对于其他VS2010应该类似。

并检查是否存在绑定错误,如果是,则是什么。

你可以

这样做:

Person _currentPerson;
public Person CurrentPerson 
{
    get { return _currentPerson; }
    set
    {
        _currentPerson = value;
        this.Title = value.FullName;
    }
}

最新更新