WPF: How to data bind an object to an element and apply a data template through code?
- by Boris
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.