Question

I'm just starting to use WPF, but my binding doesn't work.
When I start the application the screen is just blank.

This is my XAML

<Window x:Class="HelloWPF.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">
<Grid>
    <ContentControl Content="{Binding PersonOne}" Width="auto" Height="auto" >
        <ContentControl.ContentTemplate>
            <DataTemplate>
                <StackPanel>
                    <TextBlock Text="{Binding FirstName}" FontSize="15" />
                    <TextBlock Text="{Binding Age}" FontSize="12" />
                </StackPanel>
            </DataTemplate>
        </ContentControl.ContentTemplate>
    </ContentControl>
</Grid>

This is the code:

public partial class MainWindow : Window
{
    public Person PersonOne;
    public MainWindow()
    {
        InitializeComponent();

        PersonOne = new Person();
        PersonOne.Gender = Gender.Female;
        PersonOne.Age = 24;
        PersonOne.FirstName = "Jane";
        PersonOne.LastName = "Joe";

        this.DataContext = this;
    }
}

And this is the person class

public class Person
{
    public string LastName { get; set; }
    public string FirstName { get; set; }

    public int Age { get; set; }
    public Gender Gender { get; set; }
}

public enum Gender
{
    Male, 
    Female
}

What am I doing wrong?

Était-ce utile?

La solution

You cannot bind to fields, only properties, so change this:

public Person PersonOne;

to this:

public Person PersonOne {get;set;}

BTW, you probably need to create a ViewModel rather than putting the Data inside the Window itself.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top