rsgmon
rsgmon

Reputation: 1932

Binding with a single Window Class

This is out of curiousity question. I know you should not structure any real WPF applications this way.

Working within and using only the MainWindow Class how do you bind an XAML element to a CLR property?

Here is my XAML.

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <TextBlock DockPanel.Dock ="Top" Height="50" Width="50"
                   Background ="AliceBlue" FontSize ="16" />
    </Grid>
</Window>

And Code

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        string _myString = "hello world";
        public string MyString
        {
            get { return _myString; }
        }

        public MainWindow()
        {
            InitializeComponent();
        }

        public event PropertyChangedEventHandler PropertyChanged;

        void OnPropertyChanged(string propName)
        {
            if (this.PropertyChanged != null)
                this.PropertyChanged(
                    this, new PropertyChangedEventArgs(propName));
        }
    }
}

So I want to display the string in the textblock. I think its a simple binding but I can't find the right syntax. Thanks

Upvotes: 0

Views: 45

Answers (2)

robertos
robertos

Reputation: 1796

In this case you can simply do:

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525"
    x:Name="MainWindow">
    <Grid>
        <TextBlock DockPanel.Dock ="Top" Height="50" Width="50"
                   Background ="AliceBlue" FontSize ="16"
                   Text="{Binding MyString, ElementName=MainWindow}" />
    </Grid>
</Window>

Upvotes: 1

Hamlet Hakobyan
Hamlet Hakobyan

Reputation: 33381

You must set your window data context to itself.

<Window.DataContext>
    <Binding RelativeSource="{RelativeSource Self}"/>
</Window.DataContext>

then you cant bind to your property MyString

<TextBlock DockPanel.Dock ="Top" Height="50" Width="50"
                Background ="AliceBlue" FontSize ="16" />

Upvotes: 1

Related Questions