【问题标题】:Binding Title of Window to text将窗口标题绑定到文本
【发布时间】:2017-08-28 12:11:25
【问题描述】:

我有一个具有“标题”属性的视图模型,并且我的数据上下文设置为此 VM。 我有一个TextBox,它需要显示窗口的标题,当我在后面的“.cs”文件中更改它时,它需要更改。 我们如何从“.cs”文件而不是 viemodel 的属性中绑定窗口的标题?

<TextBlock VerticalAlignment="Top" HorizontalAlignment="Left"
           Text="{Binding Title,RelativeSource={RelativeSource FindAncestor,AncestorType=Window}}" 
           Margin="10,8,0,0"/>

我正在从MSDN example取样

【问题讨论】:

  • Textbox.Text 是否绑定到VM.Title?如果是这样,为什么要从代码隐藏中更改Textbox.Text
  • 一些代码会有所帮助。

标签: c# wpf xaml viewmodel


【解决方案1】:

试试这个:

<Window ... Title="{Binding TitleProperty, RelativeSource={RelativeSource Self}}"

如果您打算使用TextBox 更改标题,则代码隐藏类应实现INotifyPropertyChanged 接口:

<Window x:Class="WpfApplication1.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Title="{Binding MyTitle, RelativeSource={RelativeSource Self}}" Height="300" Width="300">
    <StackPanel>
        <TextBox Text="{Binding MyTitle, UpdateSourceTrigger=PropertyChanged, RelativeSource={RelativeSource AncestorType=Window}}" />
    </StackPanel>
</Window>

public partial class Window1 : Window, INotifyPropertyChanged
{
    public Window1()
    {
        InitializeComponent();
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }

    private string _title;
    public string MyTitle
    {
        get { return _title; }
        set { _title = value; NotifyPropertyChanged(); }
    }
}

【讨论】: