murmansk murmansk - 27 days ago 113
C# Question

Binding Title of Window to text

I have one viewmodel which has "title" property and my datacontext is set to this VM.
I have a

TextBox
which need to show Title of window and it need to change when I am channgin it in ".cs " file behind.
How can we bind title of window from property from ".cs" file and not from viemodel?

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


I am taking sample from MSDN example

mm8 mm8
Answer Source

Try this:

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

The code-behind class should implement the INotifyPropertyChanged interface if you intend to be able to change the title using the 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(); }
    }
}