【发布时间】:2010-07-28 23:49:07
【问题描述】:
我目前正在将 xml 文件绑定到 C# WPF 中的列表框。在 itemtemplate 中,我添加了控件。如下:
<DataTemplate x:Key="SinglecueTemplate">
<Grid Height="30" Width="425" Margin="3,3,0,3">
<Button Content="{Binding XPath=nr}" Width="30" Style="{DynamicResource CUEStyle_Button_Inhoudknopje}" Template="{DynamicResource CUEStyle_singlecueknopnummer}" Height="Auto" HorizontalAlignment="Left" Background="#FFABCCED" Foreground="White" IsEnabled="False"/>
<TextBlock x:Name="name" Margin="54,0,114.667,0" Width="Auto" VerticalAlignment="Center" FontSize="16" Foreground="Gray" Text="{Binding XPath=Name}"/>
<Button x:Name="playbutton" Width="30" Style="{DynamicResource CUEStyle_Button_Groot}" Template="{DynamicResource CUEStyle_Rondknopje}" Height="Auto" HorizontalAlignment="Right" Margin="0,0.55,74.737,-0.55" Content="u" FontFamily="Wingdings 3" Foreground="#FF0178D3" Opacity="1" BorderBrush="#FF0178D3" Click="playcue"/>
<Button Width="30" Style="{DynamicResource CUEStyle_Button_Groot}" Template="{DynamicResource CUEStyle_Rondknopje}" Height="Auto" HorizontalAlignment="Right" Margin="0,0.55,37.071,-0.55" Content="¢" FontFamily="Wingdings 2" Foreground="Gray" Opacity="0.4"/>
<Button Width="15" Style="{DynamicResource CUEStyle_Button_Groot}" Template="{DynamicResource CUEStyle_kleinloopje}" Height="15" HorizontalAlignment="Left" Margin="15,0,0,-5.5" Content="Q" FontFamily="Wingdings 3" Foreground="White" FontWeight="Bold" FontSize="10.667" Opacity="1" VerticalAlignment="Bottom" BorderBrush="{x:Null}" Background="{x:Null}" IsEnabled="{Binding XPath=Loop}"/>
<TextBlock Margin="0,0,114.667,0" Width="81.07" VerticalAlignment="Center" FontSize="16" Foreground="Gray" Text="03:02:11" HorizontalAlignment="Right"/>
</Grid>
</DataTemplate>
现在,当单击播放按钮时,我想访问该列表框项中的其他属性,例如文本块中的文本。我查看了如何做到这一点,并提出了以下建议:
private void playcue(object sender, System.Windows.RoutedEventArgs e)
{
Button playcue = (Button)sender;
Textbox titel = (Textbox)playcue.DataContext;
MessageBox.Show(titel);
}
但是上面的代码给了我一个错误,指出类型文本框是未知的。我是否必须对数据模板做一些事情才能访问模板中的其他项目?或者是否可以从数据源访问兄弟节点?
更新
找到答案。现在供将来参考:
private void playcue(object sender, System.Windows.RoutedEventArgs e)
{
Button playcue = (Button)sender;
XmlElement name = (XmlElement)playcue.DataContext;
MessageBox.Show(name.InnerText);
}
从项目中返回所有同级值
如果您想访问特定的同级,可以这样做:
MessageBox.Show(name.SelectSingleNode("Name").InnerXml);
【问题讨论】: