Help with WPF data binding

I am new to WPF and I am trying to understand how data binding works, but I'm not very lucky.

I'm trying to start with something simple - binding the contents of a text field to a string variable in my program.

I read many, many pages of MSDN documentation about data binding, XML namespaces, markup extensions, resources, dependency properties, and much more, and I still can't get it working.

Here is my MainWindow.xaml:

<Window x:Class="WpfTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:c="clr-namespace:WpfTest"
        Title="MainWindow">
    <Grid>
        <Grid.Resources>
            <c:Foo x:Key="MyFoo"/>
        </Grid.Resources>
        <TextBox Width="100" Height="28"
                 Text="{Binding Source=MyFoo,
                                Path=BarProperty,
                                Mode=TwoWay,
                                UpdateSourceTrigger=PropertyChanged}"/>
    </Grid>
</Window>

And my MainWindow.xaml.cs:

namespace WpfTest
{
    public class Foo : DependencyObject
    {
        public static readonly DependencyProperty BarProperty = DependencyProperty.Register("Bar", typeof(String), typeof(Foo));

        public String Bar
        {
            get { return (String)GetValue(BarProperty); }
            set { SetValue(BarProperty, value); }
        }
    }

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            MyFoo = new Foo { Bar = "hello" };
        }

        public Foo MyFoo { get; set; }
    }
}

I expect the text box to show "hello" when the program starts, but it is empty.

Can someone tell me what I'm doing wrong?

+3
source share
2 answers

You need to specify the source. Or:

, Name= "mywin", witn ElementName = "myWin"

DataContext :

DataContext = "{Binding ElementName =" myWin "} - RelativeSource, , , , - , , , :)

:

http://blogs.msdn.com/b/wpfsdk/archive/2006/10/19/wpf-basic-data-binding-faq.aspx

+1

DataContext .

public MainWindow()
{
    InitializeComponent();
    this.DataContext = this;
    MyFoo = new Foo { Bar = "hello" };
}

WPF .

DataContext, : " , ... , , DataContext MainWindow , MainWindow MainWindow.

+3

All Articles