Search code examples
c#wpfbindingdatacontext

How to set a class in the DataContext with XAML?


I have a WPF forms and a class Users (content attributes Id, Login and Name), in my class of this forms, I had get a Users object for put this information in the form with DataContext and Binding

I can put this Users object to my Window.DataContext (this.DataContext = usersObject;) with code behind, but I think if I can make this with XAML, maybe is better

I have set a attribute in my class UserForm (public Users usersObject {get; set;})

My form UserForm : Window

<Window DataContext="{What need I put here?">
    <Grid>
        <TextBlock Text="Id:"/>
        <TextBox Name="Id" Text="{Binding Path=Id}"/>

        <TextBlock Text="Login:"/>
        <TextBox Name="Login" Text="{Binding Path=Login}"/>

        <TextBlock Text="Name:"/>
        <TextBox Name="Name" Text="{Binding Path=Name}"/>
    </Grid>
</Window>

UserForm.xaml.cs

public class UserForm : Window
{
    public Users userObject { get; set; }

    public UserForm(Users user)
    {
        InitializeComponent();
        this.userObject = user;
    }
}

My class Users

public class Users
{
    public int Id { get; set; }
    public string Login { get; set; }
    public string Name { get; set; }
}

How to I do for set userObject in the itself Window.DataContext for TextBox's can put it values?


Solution

  • Some time back I had written an article on different options of binding XAML control to code behind property. This might help you.

    http://codingseason.blogspot.in/2013/05/data-binding-xaml-control-to-property.html