C# 在SilverLight5中找不到DataTemplate内的控件

C# 在SilverLight5中找不到DataTemplate内的控件,c#,datatemplate,silverlight-5.0,itemscontrol,C#,Datatemplate,Silverlight 5.0,Itemscontrol,我使用的是DataTemplate,其中我声明了两个按钮,默认情况下它们是不可见的。现在我想根据某些条件使它们在代码隐藏中可见,但我找不到这些控件 以下是我的代码: XAML: 所以我想知道我到底需要找到ItemsControl?如果是这样,为什么我找不到这些按钮 我也试过了 var findControl=temControl.ItemContainerGenerator.ContainerFromIndex(索引)但结果相同(Null)。您可以使用Template.FindName(字符串名

我使用的是
DataTemplate
,其中我声明了两个
按钮,默认情况下它们是不可见的。现在我想根据某些条件使它们在代码隐藏中可见,但我找不到这些控件

以下是我的代码:

XAML:

所以我想知道我到底需要找到
ItemsControl
?如果是这样,为什么我找不到这些按钮

我也试过了
var findControl=temControl.ItemContainerGenerator.ContainerFromIndex(索引)
但结果相同(
Null
)。

您可以使用
Template.FindName(字符串名称)轻松地从后面获取控件

<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>
System.Windows.Controls.ItemsControl itemControl = (from sp in selectedTreeViewItem.GetVisualDescendants().OfType<System.Windows.Controls.ItemsControl>()
                                                    where sp.Name == "SynonymsItemsControl"
                                                    select sp).FirstOrDefault();
Button AddSynonymsBtn = (from btn in itemControl.GetVisualDescendants().OfType<Button>()
                         where btn.Name == "AddSynonymsBtn"
                         select btn).FirstOrDefault();
private Button _partSynonyms = null;

public MyControlTemplate{
   Loaded += (sender, e) => OnLoaded();
}

private void OnLoaded(){
   _partSynonyms = (Button)Template.FindName("PART_AddSynonymsBtn"); //You "should" use PART_ as a prefix in a Template
  if(_partSynonyms == null)
     //Button not found -> Log some error but you should not throw an exception
}