user1688773
user1688773

Reputation: 157

How to bind WPF TextBox to a propperty that is the member of application main window

I have a private field

private static Double myValue;

in the application MainWindow class. And there (in the MainWindow class) I defined a property

public static Double MytValue
{
    get { return myValue; }
}

In the structure of the MainWindow class I have a TextBox. I'm in need of binding it to the MytValue property. In XAML I write:

<TextBox Name="tbxMyValue" Grid.Row="1" Grid.Column="2" TextAlignment="Center"
         Text="{Binding Path=MyValue}" Width="Auto" Margin="10,0,10,15" IsEnabled="True" />

But it has no effect. I see nothing in the TextBox while myValue variable has a value. Why? Please help me.

Upvotes: 2

Views: 11815

Answers (4)

paparazzo
paparazzo

Reputation: 45096

I like to set the DataContext in the Window section

<Window x:Class="Gabe3a.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:Gabe3a"
        xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase"
        xmlns:System="clr-namespace:System;assembly=mscorlib"
        DataContext="{Binding RelativeSource={RelativeSource self}}"
        Title="Gabriel Main Ver 3a01" Icon="faviconw.ico" Height="600" Width="800">

Upvotes: 5

Rachel
Rachel

Reputation: 132558

You need to set the DataContext behind the Window for that binding to work

There are two layers to an application with WPF: the UI layer and the data layer.

The Data layer for an application starts out as null, and you can set it using the DataContext property.

Whenever you do a basic binding in WPF, you are binding to the DataContext. So Text="{Binding Path=MyValue}" is actually saying "Get the MyValue property from the current DataContext".

You could simply set the DataContext in your code behind:

MyWindow.DataContext = this;

Or you can use a RelativeSource binding to tell WPF to get the MyValue property from somewhere else, such as telling it to get it from the closest Window it finds when navigating up the VisualTree:

Text="{Binding Path=MyValue, RelativeSource={
    RelativeSource AncestorType={x:Type Window}}}"

I actually have an article on my blog about the DataContext that I'd recommend reading if you're new to WPF and the DataContext: What is this "DataContext" you speak of?

Upvotes: 4

kmatyaszek
kmatyaszek

Reputation: 19296

In file MainWindow.xaml.cs in constructor add this line:

DataContext = this;

after InitializeComponent();

Upvotes: 0

Erti-Chris Eelmaa
Erti-Chris Eelmaa

Reputation: 26268

It's not how it works. Binding to static properties; {Binding Source={x:Static local:Application.MyValue}}

Note that your field needs to be property & public. If you want to go with your solution, you need to set DataContext as {RelativeSource Self}.

Upvotes: 0

Related Questions