<!-- DataTemplate 資源 -->
<DataTemplate x:Key="DataTemplatePopList">
<Grid d:DesignWidth="99" d:DesignHeight="148" Height="130" Width="130">
<Button x:Name="VoteButton" Content="投票" />
<TextBlock x:Name="VoteTextBlock" Text="{Binding ObjectBills}" />
<Image x:Name="VoteImage" Source="{Binding ImageSource}" />
</Grid>
</DataTemplate>
<!-- 使用DataTemplate資源 -->
<ListBox x:Name="VoteListBox" ItemTemplate="{StaticResource DataTemplatePopList}" />
//取得DataTemplate中的控制項
ListBoxItem voteListBoxItem = (ListBoxItem)(VoteListBox.ItemContainerGenerator.ContainerFromItem(VoteListBox.SelectedItem));
TextBlock voteTextBlock = FindVisualChild<TextBlock>(voteListBoxItem, "VoteTextBlock");
//尋找視覺化樹下的子項目
private childItem FindVisualChild<childItem>(DependencyObject obj, String childName) where childItem : DependencyObject
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(obj, i);
if (child != null &&
child is childItem &&
child.GetValue(NameProperty).ToString() == childName)
return (childItem)child;
else
{
childItem childOfChild = FindVisualChild<childItem>(child, childName);
if (childOfChild != null)
return childOfChild;
}
}
return null;
}
沒有留言:
張貼留言