【问题标题】:Unable to find controls inside DataTemplate in SilverLight5在 SilverLight5 的 DataTemplate 中找不到控件
【发布时间】: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


    【解决方案1】:

    您可以使用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
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-26
      • 1970-01-01
      • 2011-09-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多