Note that there are some explanatory texts on larger screens.

plurals
  1. POWPF Binding to UserControl Custom DependencyProperty
    primarykey
    data
    text
    <p>I have a custom UserControl called SongDescription:</p> <pre><code>&lt;UserControl x:Class="DPTestAp.SongDescription" ...&gt; &lt;Grid x:Name="LayoutRoot"&gt; &lt;DockPanel Height="50"&gt; &lt;TextBlock x:Name="title" Text="{Binding name}" Width="100" Height="30"/&gt; &lt;TextBox x:Name="lyrics"/&gt; &lt;/DockPanel&gt; &lt;/Grid&gt; &lt;/UserControl&gt; </code></pre> <p>I added DependencyProperty to it:</p> <pre><code>public partial class SongDescription : UserControl { public static readonly DependencyProperty SongProperty = DependencyProperty.Register("Song", typeof(Song), typeof(SongDescription)); public Song Song { get { return (Song)GetValue(SongProperty); } set { SetValue(SongProperty, value); updateLyrics() } } private void updateLyrics() { lyrics.Text = Song.lyrics; } public SongDescription() { InitializeComponent(); } } </code></pre> <p>The question is: how to bind something to this SongProperty? I use SongDescription in my main window like this:</p> <pre><code>&lt;local:SongDescription x:Name="songDescription" Song="{Binding DataContext}"/&gt; </code></pre> <p>I cannot make my TextBox <em>lyrics</em> show lyrics. In main window I tried to set DataContext to songDescription, like this:</p> <pre><code>songDescription.DataContext = new Song() { name="Home", lyrics="Hold on, to me as we go" }; </code></pre> <p>or to window itself like this:</p> <pre><code>DataContext = new Song() { name="Home", lyrics="Hold on, to me as we go" }; </code></pre> <p>I even tried to make Song a resource and bind it to SongProperty like this:</p> <pre><code>&lt;Window.Resources&gt; &lt;local:Song x:Key="res" name="Home" lyrics="Hold on, to me as we go"/&gt; &lt;/Window.Resources&gt; &lt;Grid&gt; &lt;local:SongDescription x:Name="songDescription" Song="{StaticResource res}"/&gt; &lt;/Grid&gt; </code></pre> <p>Nothing helped. TextBlock <em>title</em> binds song name fine. But I can't make updateLyrics() method be called. (In real life this method is more complicated, so I can't use Binding like with name).</p> <p>Thank you!</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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