代码之家  ›  专栏  ›  技术社区  ›  murmansk

将窗口标题绑定到文本

  •  -2
  • murmansk  · 技术社区  · 8 年前

    我有一个viewmodel,它具有“title”属性,我的datacontext设置为这个VM。 TextBox 它需要显示窗口的标题,当我在后面的“.cs”文件中更改时,它需要更改。

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

    我正在从 MSDN example

    1 回复  |  直到 8 年前
        1
  •  2
  •   mm8    8 年前

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

    代码隐藏类应该实现 INotifyPropertyChanged TextBox :

    <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(); }
        }
    }