Ho un UserControl personalizzata denominata SongDescription:WPF Associazione a UserControl personalizzato DependencyProperty
<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>
ho aggiunto DependencyProperty ad esso:
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();
}
}
La domanda è: come associare qualcosa a questo SongProperty? Io uso SongDescription nella mia finestra principale in questo modo:
<local:SongDescription x:Name="songDescription" Song="{Binding DataContext}"/>
non riesco a fare il mio TextBox testi spettacolo testi. Nella finestra principale ho cercato di impostare DataContext a songDescription, in questo modo:
songDescription.DataContext = new Song() { name="Home", lyrics="Hold on, to me as we go" };
o finestra stessa in questo modo:
DataContext = new Song() { name="Home", lyrics="Hold on, to me as we go" };
ho anche provato a fare canzone una risorsa e associarlo al SongProperty come questo :
<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>
Niente di utile. TextBlock title associa il nome del brano. Ma non posso far chiamare il metodo updateLyrics(). (Nella vita reale questo metodo è più complicato, quindi non posso usare Binding come con il nome).
Grazie!
Grazie, maestro! –
ma poi, è il callback 'PropertyChanged', non sarò in grado di aggiornare alcun controllo, perché è una funzione condivisa! –