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.
The minimum to get this to work is to add the line:
But you’ve got few things that may cause you problems later.
The
DataContextsetting 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
Testsis a property of whatever class you use as theDataContext. You want to make the DataContext the only thing you set in code, then everything else flows from the bindings.Instead of
List, you probably want to useObservableCollection, so that the data binding engine will automatically be informed when items are added and removed from the collection.