【发布时间】:2015-05-26 20:40:43
【问题描述】:
我使用DataTemplate 声明了两个Buttons,默认情况下它们是不可见的。现在我想根据某些条件在后面的代码中将它们设为Visible,但我无法找到这些控件。
以下是我的代码:
XAML:
<ItemsControl x:Name="SynonymsItemsControl" ItemsSource="{Binding Synonyms}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" Margin="0,5,0,0" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel x:Name="SynonymsStackPanel">
<CheckBox x:Name="SynonymsChkBx" Content="{Binding Display}" Margin="10,0,0,0" />
WANT TO FIND THESE TWO BUTTONS
<Button x:Name="AddSynonymsBtn" Margin="525, 0, 0, 0" ToolTipService.ToolTip="Add Synonyms" Visibility="Collapsed">
<Image Source="/Images/AddSynonyms.png" Height="24"/>
</Button>
<Button x:Name="CancelSynonymsBtn" Margin="600, 0, 0, 0" ToolTipService.ToolTip="Cancel Synonyms" Visibility="Collapsed">
<Image Source="/Images/CancelSynonyms.png" Height="24"/>
</Button>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
代码隐藏:
我可以通过这样做找到 ItemControl,
System.Windows.Controls.ItemsControl itemControl = (from sp in selectedTreeViewItem.GetVisualDescendants().OfType<System.Windows.Controls.ItemsControl>()
where sp.Name == "SynonymsItemsControl"
select sp).FirstOrDefault();
现在,当我想查找在 ItemsControl->DataTemplate 中声明的按钮时,它是 Null
Button AddSynonymsBtn = (from btn in itemControl.GetVisualDescendants().OfType<Button>()
where btn.Name == "AddSynonymsBtn"
select btn).FirstOrDefault();
所以我想知道我是否需要找到ItemsControl?如果是这样,那为什么我找不到这些按钮?
我也试过
var findControl = temControl.ItemContainerGenerator.ContainerFromIndex(index); 但结果相同(Null)。
【问题讨论】:
标签: c# datatemplate silverlight-5.0 itemscontrol