Note that there are some explanatory texts on larger screens.

plurals
  1. POWPF: How to data bind an object to an element and apply a data template through code?
    text
    copied!<p>I have created a class <code>LeagueMatch</code>. </p> <pre><code>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() { } } </code></pre> <p>Next, I have defined a datatemplate resource for <code>LeagueMatch</code> objects in XAML:</p> <pre><code>&lt;DataTemplate x:Key="MatchTemplate" DataType="{x:Type entities:LeagueMatch}"&gt; &lt;Grid Name="MatchGrid" Width="140" Height="50" Margin="5"&gt; &lt;Grid.RowDefinitions&gt; &lt;RowDefinition Height="*" /&gt; &lt;RowDefinition Height="*" /&gt; &lt;RowDefinition Height="*" /&gt; &lt;/Grid.RowDefinitions&gt; &lt;TextBlock Grid.Row="0" Text="{Binding Home}" /&gt; &lt;TextBlock Grid.Row="1" Text="- vs -" /&gt; &lt;TextBlock Grid.Row="2" Text="{Binding Visitor}" /&gt; &lt;/Grid&gt; &lt;/DataTemplate&gt; </code></pre> <p>In the XAML code-behind, I want to create a <code>ContentPresenter</code> object and to set it's data binding to a previously initialized <code>LeagueMatch</code> object and apply the defined data template. How is that supposed to be done? Thanks. </p> <h2>Solution</h2> <pre><code>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); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload