I have a custom UserControl called SongDescription:
<UserControl x:Class="DPTestAp.SongDescription" ...> <Grid x:Name="LayoutRoot"> <DockPanel Height="50"> <TextBlock x:Name="title" Text="{Binding name}" Width="100" Height="30"/> <TextBox x:Name="lyrics"/> </DockPanel> </Grid> </UserControl>
I added DependencyProperty to it:
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(); } }
Question: how to connect something with this SongProperty? I use SongDescription in my main window as follows:
<local:SongDescription x:Name="songDescription" Song="{Binding DataContext}"/>
I can not make text TextBox lyrics. In the main window, I tried to set the DataContext to songDescription, for example:
songDescription.DataContext = new Song() { name="Home", lyrics="Hold on, to me as we go" };
or in order to make the window look:
DataContext = new Song() { name="Home", lyrics="Hold on, to me as we go" };
I even tried to make Song a resource and associate it with SongProperty as follows:
<Window.Resources> <local:Song x:Key="res" name="Home" lyrics="Hold on, to me as we go"/> </Window.Resources> <Grid> <local:SongDescription x:Name="songDescription" Song="{StaticResource res}"/> </Grid>
Nothing helped. The TextBlock header binds the song name in order. But I can not call the updateLyrics () method. (In real life, this method is more complicated, so I can not use Binding, as with a name).
Thanks!