spiderplant0
spiderplant0

Reputation: 3952

Cant get DataBinding in XAML to work

I'm learning WPF and investigating DataBinding. I want to see how to specify the DataBinding in XAML rather than in C# but cant figure out what I'm doing wrong in the example below.

(I know there are many questions like this already, but I've gone through them all but cant get any of the suggestions to work).

<Window x:Class="DataBinding2.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="theMainWindow"
    xmlns:local="clr-namespace:DataBinding2"
    >

<StackPanel>
        <WrapPanel Name="WrapPanel1" Orientation="Vertical" Margin="10" >

            <!--// Tried this but get error: The type 'local:person2' was not found. --> 
            <WrapPanel.DataContext>
                <local:person2 />
            </WrapPanel.DataContext>

        <TextBlock Text="{Binding Path=FirstName}"/>
    </WrapPanel>

namespace DataBinding2
{
    public partial class MainWindow : Window
    {
        public Person person2;  

        public MainWindow()
        {
            person2 = new Person()
            {
                FirstName = "Bob",
            };

            InitializeComponent();

            // This works - but want to know what alternative is to do it in XAML
            //WrapPanel1.DataContext = person2;
        }
    }

    public class Person
    {
        public string FirstName { get; set; }
        public int Age { get; set; }
    }

Upvotes: 0

Views: 38

Answers (1)

Rohit Vats
Rohit Vats

Reputation: 81313

You can set DataContext to only instance and not directly to property within some instance from XAML.

For that to work first make person2 a property since binding only works with properties at least for instance objects:

public Person person2 { get; set; }

and then you can set DataContext in XAML like this:

<WrapPanel Name="WrapPanel1" Orientation="Vertical" Margin="10"
           DataContext="{Binding person2, ElementName=theMainWindow}">

Upvotes: 2

Related Questions