我正在使用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
- &gt; 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
)。
答案 0 :(得分:0)
您可以使用Template.FindName(string Name);
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
}