chobo2
chobo2

Reputation: 85765

How to do data binding?

I am trying to do some simple data binding in XAML but it is not working for me and I am not sure why.

I have this gridview

 <GridView Name="test2">
            <GridView.ItemTemplate>
                <DataTemplate>
                    <StackPanel>
                        <TextBlock Text="{Binding Header}" FontWeight="Bold" Style="{StaticResource ItemTextStyle}"/>
                        <TextBlock Text="{Binding Item}" FontWeight="Bold" Style="{StaticResource ItemTextStyle}"/>
                    </StackPanel>
                </DataTemplate>
            </GridView.ItemTemplate>
            <GridView.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel Orientation="Horizontal"/>
                </ItemsPanelTemplate>
            </GridView.ItemsPanel>
        </GridView>

I am trying to now bind. I tried to do it in XMAL(it crashes) and through C# code(Nothing happens)

In the code behind constructor I tried to do this

 public MyPage()
        {
            this.InitializeComponent();

            Test t = new Test
            {
                Header = "Header 1",
                Item = "Item 1",

            };

            List<Test> ts = new List<Test>();
            ts.Add(t);
            test2.DataContext = t;

        }

I also tried to pass it an collection as well.

As I said I could not get the XMAL way to do it at all.

Upvotes: 0

Views: 120

Answers (2)

Jim O&#39;Neil
Jim O&#39;Neil

Reputation: 23764

The minimum to get this to work is to add the line:

test2.ItemsSource = ts;

But you've got few things that may cause you problems later.

  1. The DataContext setting doesn't make much sense here, you're saying that you're going to make a single item the context for elements you're bind to a grid. Typically, I'd say the DataContext would be a class that contains your collection of Tests - that would be the DataContext of your page, for instance, then you'd have

    <GridView Name="test2" ItemsSource="{Binding Tests}">

    where Tests is a property of whatever class you use as the DataContext. You want to make the DataContext the only thing you set in code, then everything else flows from the bindings.

  2. Instead of List, you probably want to use ObservableCollection, so that the data binding engine will automatically be informed when items are added and removed from the collection.

Upvotes: 1

devuxer
devuxer

Reputation: 42364

I believe you need to bind the ItemsSource of your GridView to the collection.

Try following these steps:

  1. Create a property on MyPage: public List<Test> Tests { get; set; }

  2. Replace test2.DataContext = t; with Tests = ts;

  3. In your XAML, add an ItemsSource property, like this:

    <GridView Name="test2" ItemsSource="{Binding Tests}">
    

Upvotes: 1

Related Questions