我有一个名为 SongDescription 的自定义 UserControl:
<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>
我向其中添加了 DependencyProperty:
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();
}
}
问题是:如何将一些东西绑定到这个 SongProperty?我在主窗口中使用 SongDescription,如下所示:
<local:SongDescription x:Name="songDescription" Song="{Binding DataContext}"/>
我无法让我的 TextBox歌词显示歌词。在主窗口中,我尝试将 DataContext 设置为 songDescription,如下所示:
songDescription.DataContext = new Song() { name="Home", lyrics="Hold on, to me as we go" };
或像这样窗口本身:
DataContext = new Song() { name="Home", lyrics="Hold on, to me as we go" };
我什至尝试让 Song 成为资源并将其绑定到 SongProperty,如下所示:
<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>
没有任何帮助。TextBlock标题很好地绑定了歌曲名称。但我不能调用 updateLyrics() 方法。(在现实生活中这种方法比较复杂,所以我不能像 name 那样使用 Binding)。
谢谢!