tags:

views:

29

answers:

2

Hi,

I can bind collection to treeveiw but I don't know hot bind one simle object to wpc control.

<UserControl x:Class="ReporterWpf.UserControl1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Height="300" Width="300">
    <Grid>
        <StackPanel>
            <TextBox Name="{Binding Path=Name}"></TextBox>
            <TextBox Name="{Binding Path=Age}"></TextBox>
        </StackPanel>
    </Grid>
</UserControl>


public Person
{
public string Name {get;set;}
public int Age {get;set;}
}

public partial class UserControl1 : UserControl
    {
        public UserControl1()
        {
            InitializeComponent();
        }
 public UserControl1(Person person):this()
        {
        Person person=new Person();
person.Age=19;
person.Name = "Patrick"
        }
    }

Which are magic lines of code to bind this two properties ?

+4  A: 

You need to set the DataContext of any of the parent elements.

For example:

this.DataContext = person;

If you want to bind two people to two different panels, you'll need to set each panel's DataContext separately. (Or bind them both to a parent object that holds the people)

SLaks
+1.. this is the simplest approach, but there are a few different options for setting the DataContext. Paul Stovell explored the options here: http://www.paulstovell.com/mvvm-instantiation-approaches
IanR
A: 

You just need give data context to the parent container which has binding expresions:

this.DataContext= person;

Where "person" instance of your class

Polaris