【问题标题】:WPF Window Title binding base on Information Class?基于信息类的 WPF 窗口标题绑定?
【发布时间】:2012-04-09 05:54:48
【问题描述】:

我有 Wpf-App 用于处理人员对象。 Person Struct 是 Sql-server 表,我在我的项目中使用 Linq-to-Sql(所以 dbml 中有类是指人)。

我有用于更新或插入人员的表单(简单模式窗口)。在这个窗口中,我有 Peoperty,它的当前值为 person。

public Person CurrentPerson { get; set; }

所以我要找的是:

如何根据CurrentPerson.FullName绑定这个窗口的标题?如果 CurrentPerson.FullName 已更改,则绝对窗口标题必须更改!

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

【问题讨论】:

    标签: c# wpf binding


    【解决方案1】:

    首先,您的代码隐藏或视图模型应该实现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 设置为自身。

    【讨论】:

    • 谢谢我没有为当前窗口设置DataContext。设置后效果很好。
    【解决方案2】:

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

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

    编辑 2:您可以为控件命名,然后在 Binding Element 中使用该名称,例如:

    <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 -&gt; Options -&gt; Debugging -&gt; Output Window -&gt; WPF Trace Settings [这是VS2010的;其他人应该是类似的。]

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

    【讨论】:

    • @Rev:哦,我错过了 Linq-to-Sql 位。这将解释否决票(这很好)。我希望我现在明白了这个问题。
    • @Rev: 不知道您是使用自定义控件作为标题栏还是常规标准窗口。
    【解决方案3】:

    你可以这样做:

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

    【讨论】:

    • @Rev 我想看看是否有人可以做到这一点,或者解释为什么它不可能。在这种情况下,似乎普通的绑定方法不起作用,但我不知道为什么。
    • 是的,我什至尝试依赖道具或转换器,但我不能这样做。我不知道该怎么做,也许有人可以帮助我!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-15
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多