I have created a class LeagueMatch.
public class LeagueMatch
{
public string Home
{
get { return home; }
set { home = value; }
}
public string Visitor
{
get { return visitor; }
set { visitor = value; }
}
private string home;
private string visitor;
public LeagueMatch()
{
}
}
Next, I have defined a datatemplate resource for LeagueMatch objects in XAML:
<DataTemplate x:Key="MatchTemplate" DataType="{x:Type entities:LeagueMatch}">
<Grid Name="MatchGrid" Width="140" Height="50" Margin="5">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Text="{Binding Home}" />
<TextBlock Grid.Row="1" Text="- vs -" />
<TextBlock Grid.Row="2" Text="{Binding Visitor}" />
</Grid>
</DataTemplate>
In the XAML code-behind, I want to create a ContentPresenter object and to set it’s data binding to a previously initialized LeagueMatch object and apply the defined data template. How is that supposed to be done? Thanks.
Solution
LeagueMatch match = new LeagueMatch("A team", "B team");
ContentPresenter contentPresenter = new ContentPresenter();
contentPresenter.ContentTemplate = this.FindResource("MatchTemplate") as DataTemplate;
Binding binding = new Binding();
binding.Source = match;
contentPresenter.SetBinding(ContentPresenter.ContentProperty, binding);
matchSlot.Children.Clear();
matchSlot.Children.Add(contentPresenter);
In code-behind:
Implementing
INotifyPropertyChangedBe sure to change your properties only by assigning to the property so the event gets executed. The binding engine is listening to those events to refresh the binding.