murmansk murmansk - 1 year ago 249
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

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}}"

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"
        Title="{Binding MyTitle, RelativeSource={RelativeSource Self}}" Height="300" Width="300">
        <TextBox Text="{Binding MyTitle, UpdateSourceTrigger=PropertyChanged, RelativeSource={RelativeSource AncestorType=Window}}" />

public partial class Window1 : Window, INotifyPropertyChanged
    public Window1()

    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(); }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download