2017-10-12 6 views
1

Im tray_ing 코드에서 UserControl의 UIElement 가져 오기 FindControl 메서드를 사용하지만 뒤에 null 개체를 가져옵니다.FindControl을 사용하여 UserControl에서 UIElement를 가져올 수 없습니다.

필자는 FindControl 메서드를 다음과 같이 호출합니다. Canvas canvas = FindControl (this, typeof (Canvas), "mPDFView"); ScrollViewer touchLayer = FindControl (this, typeof (ScrollViewer), "mtouchLayer");

FindControl 메서드는 여기서

public static T FindControl<T>(UIElement parent, Type targetType, string ControlName) where T : FrameworkElement 
    { 
     if (parent == null) return null; 

     if (parent.GetType() == targetType && ((T)parent).Name == ControlName) 
     { 
      return (T)parent; 
     } 
     T result = null; 
     int count = VisualTreeHelper.GetChildrenCount(parent); 
     for (int i = 0; i < count; i++) 
     { 
      UIElement child = (UIElement)VisualTreeHelper.GetChild(parent, i); 

      if (FindControl<T>(child, targetType, ControlName) != null) 
      { 
       result = FindControl<T>(child, targetType, ControlName); 
       break; 
      } 
     } 
     return result; 
    } 

내 XAML

<UserControl 
x:Class="SalesApp.Views.DocViewer" 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
xmlns:local="using:SalesApp.Views" 
xmlns:uc="using:SalesApp.Views.UserControls" 
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
xmlns:vm="using:SalesApp.ViewModels" 
x:Name="root" 
mc:Ignorable="d" 
d:DesignHeight="300" 
d:DesignWidth="400"> 

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> 
    <ContentControl x:Name="contentControl" Content="{Binding Item}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch"> 
     <ContentControl.Resources> 
      <DataTemplate x:Key="Media"> 
       <Grid Background="Black"> 
        <MediaElement Source="{Binding MediaSource}" Volume="10" AreTransportControlsEnabled="True" /> 
        <StackPanel HorizontalAlignment="Right" VerticalAlignment="Top" Orientation="Horizontal" Visibility="{Binding ShowActionBar, Converter={StaticResource BoolToVisibilityConverter}}" Margin="0,12,12,0"> 
         <Button Command="{Binding EmailCommand}" Style="{StaticResource NoBorderButtonStyle}" BorderThickness="0" Visibility="{Binding IsEmailVisible, Converter={StaticResource BoolToVisibilityConverter}}"> 
          <BitmapIcon UriSource="/Assets/icons/icMail.png" Width="50" Height="50" Foreground="{ThemeResource IconsPrimary}"/> 
         </Button> 
         <Button Command="{Binding CloseCommand}" Style="{StaticResource NoBorderButtonStyle}" BorderThickness="0" Margin="0"> 
          <BitmapIcon UriSource="/Assets/icons/icClose(1).png" Width="50" Height="50" Foreground="{ThemeResource IconsPrimary}"/> 
         </Button> 
        </StackPanel> 
       </Grid> 
      </DataTemplate> 
      <DataTemplate x:Key="Image"> 
       <Grid Background="Black"> 
        <Image Source="{Binding MediaSource}" /> 
        <StackPanel HorizontalAlignment="Right" VerticalAlignment="Top" Orientation="Horizontal" Visibility="{Binding ShowActionBar, Converter={StaticResource BoolToVisibilityConverter}}" Margin="0,12,12,0"> 
         <Button Command="{Binding HDCommand}" Style="{StaticResource NoBorderButtonStyle}" BorderThickness="0" Visibility="{Binding IsLowDefinition, Converter={StaticResource BoolToVisibilityConverter}}"> 
          <TextBlock Text="HD" FontSize="35" FontWeight="ExtraBlack" Foreground="White" Margin="0,-4,0,4" /> 
         </Button> 
         <Button Command="{Binding EmailCommand}" Style="{StaticResource NoBorderButtonStyle}" BorderThickness="0" Visibility="{Binding IsEmailVisible, Converter={StaticResource BoolToVisibilityConverter}}"> 
          <BitmapIcon UriSource="/Assets/icons/icMail.png" Width="50" Height="50" Foreground="{ThemeResource IconsPrimary}"/> 
         </Button> 
         <Button Command="{Binding CloseCommand}" Style="{StaticResource NoBorderButtonStyle}" BorderThickness="0" Margin="0"> 
          <BitmapIcon UriSource="/Assets/icons/icClose(1).png" Width="50" Height="50" Foreground="{ThemeResource IconsPrimary}"/> 
         </Button> 
        </StackPanel> 
       </Grid> 
      </DataTemplate> 
      <DataTemplate x:Key="Pdf"> 
       <Grid> 
        <Grid.Resources> 
         <CollectionViewSource x:Name="viewSource" Source="{Binding Pages}" /> 
        </Grid.Resources> 

         <Canvas x:Name="mPDFView" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Tapped="FlipView_Tapped" ScrollViewer.HorizontalScrollMode="Disabled" /> 
        <ScrollViewer x:Name="mtouchLayer" Background="Transparent" IsHitTestVisible="True" Tapped="FlipView_Tapped" ScrollViewer.HorizontalScrollMode="Disabled" ScrollViewer.VerticalScrollMode="Disabled"/> 
        <ListView x:Name="pdfThumbnailList" SelectedIndex="{Binding selectedItem}" ScrollViewer.HorizontalScrollBarVisibility="Visible" ScrollViewer.HorizontalScrollMode="Enabled" ScrollViewer.VerticalScrollMode="Disabled" ItemsSource="{Binding Source={StaticResource viewSource}}" Height="150" Background="DarkGray" VerticalAlignment="Bottom" Visibility="Collapsed" Tapped="ThumbnailItemTapped" SelectionChanged="ThumbnailList_SelectionChanged"> 
         <ListView.ItemContainerStyle> 
          <Style TargetType="ListViewItem"> 
           <Setter Property="Margin" Value="0" /> 
           <Setter Property="Padding" Value="0" /> 
           <Setter Property="VerticalContentAlignment" Value="Stretch" /> 
           <Setter Property="VerticalAlignment" Value="Stretch" /> 
           <Setter Property="Height" Value="150" /> 
          </Style> 
         </ListView.ItemContainerStyle> 
         <ListView.ItemTemplate> 
          <DataTemplate> 
           <Image Stretch="Uniform"> 
            <Image.Source> 
             <BitmapImage UriSource="{Binding ImageSource}" /> 
            </Image.Source> 
           </Image> 
          </DataTemplate> 
         </ListView.ItemTemplate> 
         <ListView.ItemsPanel> 
          <ItemsPanelTemplate> 
           <VirtualizingStackPanel Orientation="Horizontal" VerticalAlignment="Stretch" /> 
          </ItemsPanelTemplate> 
         </ListView.ItemsPanel> 
        </ListView> 
        <StackPanel x:Name="pdfActionBar" HorizontalAlignment="Right" VerticalAlignment="Top" Orientation="Horizontal" Visibility="Collapsed" Margin="0,12,12,0"> 
         <uc:DocMenuBarUserControl DataContext="{Binding DocMenuVM}" /> 
         <Button Command="{Binding CloseCommand}" Style="{StaticResource NoBorderButtonStyle}" BorderThickness="0" Visibility="{Binding ShowCloseAction, ElementName=root, Converter={StaticResource BoolToVisibilityConverter}}"> 
          <BitmapIcon UriSource="/Assets/icons/icClose(1).png" Width="50" Height="50" Foreground="{ThemeResource SalesappsPrimary}"/> 
         </Button> 
         <Button Command="{Binding OpenCommand}" Style="{StaticResource NoBorderButtonStyle}" BorderThickness="0" Visibility="{Binding ShowCloseAction, ElementName=root, Converter={StaticResource InverseBoolToVisibilityConverter}}"> 
          <BitmapIcon UriSource="/Assets/icons/icFullscreen.png" Width="50" Height="50" Foreground="{ThemeResource SalesappsPrimary}"/> 
         </Button> 
        </StackPanel> 
       </Grid> 

      </DataTemplate> 

     </ContentControl.Resources> 
     <ContentControl.ContentTemplateSelector> 
      <local:DocumentTemplateSelector /> 
     </ContentControl.ContentTemplateSelector> 
    </ContentControl> 

    <Border x:Name="trainingPopup" Background="White" BorderBrush="Gray" BorderThickness="1" Visibility="Collapsed" Height="400" Width="700" CornerRadius="5" > 
     <Grid Margin="19"> 
      <Grid.RowDefinitions> 
       <RowDefinition Height="Auto" /> 
       <RowDefinition Height="*" /> 
       <RowDefinition Height="Auto" /> 
      </Grid.RowDefinitions> 
      <TextBlock Text="{Binding DataContext.Translations.training_popup_title, ElementName=contentControl}" FontSize="24" /> 
      <WebView x:Name="trainingWebContent" Grid.Row="1" ScrollViewer.VerticalScrollMode="Auto" ScrollViewer.HorizontalScrollMode="Disabled"> 
      </WebView> 
      <Button Content="{Binding DataContext.Translations.general_close,ElementName=contentControl}" HorizontalAlignment="Right" Click="closeTrainingClick" Grid.Row="2" RequestedTheme="Light" Margin="0,19,0,0" BorderBrush="Black" BorderThickness="1" /> 
     </Grid> 
    </Border> 
</Grid> 

+0

@mjwills XAML을 사용하여 게시물을 upted했습니다 –

+0

[방법 : ControlTemplate 생성 요소 찾기 | Microsoft Docs] (https://docs.microsoft.com/en-us/dotnet/framework/wpf/controls/how-to-find-controltemplate-generated-elements) – lindexi

답변

0

내가 FindControl 메서드 이런 식으로 호출 M : 캔버스 캔버스 =의 FindControl (이의 typeof (캔버스) , "mPDFView"); 다음과 같이

첫째, 당신은 FindControl 잘못 호출하는 방법은, 당신이 그것을 호출해야합니다 :이 외에도

Canvas canvas = FindControl<Canvas>(this, typeof(Canvas), "mPDFView"); 

를, 코드 조각은 올바른 것입니다. 그것은 내 편이 잘 돌아 간다.

그러나 위의 XAML 코드에서 사용하기위한 선택된 DataTemplate 결정하는 DataTemplateSelector과 함께 ContentControlDataTemplates을 가지고 니펫을한다는주의를 기울입니다. Canvas 요소는 DataTemplate이라는 이름의 Pdf에만 있고 Pdf 요소 만 선택하면 Canvas 요소를 얻을 수 있습니다. 그렇지 않으면 DataTemplate을 선택하면 시각적 트리에 Canvas 요소가 포함되지 않습니다.

null 값이 반환되는 가장 큰 이유는 현재 선택된 DataTemplatePdf이 아니기 때문입니다.

DocumentTemplateSelector 상대 코드 스 니펫을 제공하지 않았으므로 항상 요소를 찾을 수있는 Pdf DataTemplate을 반환하는 간단한 코드를 만듭니다.

<ContentControl.ContentTemplateSelector> 
    <local:DocumentTemplateSelector FirstTemplate="{StaticResource Pdf}" SecondTemplate="{StaticResource Image}"/> 
</ContentControl.ContentTemplateSelector> 

public class DocumentTemplateSelector : DataTemplateSelector 
{ 
    public DataTemplate FirstTemplate { get; set; } 
    public DataTemplate SecondTemplate { get; set; } 

    protected override DataTemplate SelectTemplateCore(object item, DependencyObject container) 
    { 
     return FirstTemplate; 
    } 
} 

ScrollViewer과 동일합니다. 문제가 지속되면 최소한의 재생산 된 프로젝트를 제공하십시오.