2017-02-22 3 views
1

У меня есть следующий ControlTemplate:WPF, не может получить доступ контроля внутри ControlTemplate

<UserControl x:Class="WpfSinergoHMIControls.Controlli.ControlButton" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
     xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
     xmlns:local="clr-namespace:WpfSinergoHMIControls.Controlli" 
     mc:Ignorable="d"> 

<UserControl.Template> 
    <ControlTemplate TargetType="UserControl" x:Name="ControlButtonTemplate"> 
     <Grid Background="Black" Name="ControlButtonGrid"> 
      <Grid.ColumnDefinitions> 
       <ColumnDefinition Width="2*" /> 
      </Grid.ColumnDefinitions> 
      <Grid.RowDefinitions> 
       <RowDefinition Height="1*" /> 
       <RowDefinition Height="2*" /> 
      </Grid.RowDefinitions> 

      <Label Content="{TemplateBinding Content}" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Background="White" Margin="1,1,1,1" Grid.Row="0"></Label> 
      <Viewbox Grid.Row="1" Margin="0" HorizontalAlignment="Center" VerticalAlignment="Center"> 
       <Ellipse Width="100" Height="100" Fill="White" Margin="0" HorizontalAlignment="Center" VerticalAlignment="Center" /> 
      </Viewbox> 
      <Viewbox Grid.Row="1" Margin="5" HorizontalAlignment="Center" VerticalAlignment="Center"> 
       <Ellipse Width="100" Height="100" Margin="0" Name="InnerEllipse" Fill="Black" HorizontalAlignment="Center" VerticalAlignment="Center"/> 
      </Viewbox> 
     </Grid> 
    </ControlTemplate> 
</UserControl.Template> 

, и я хотел бы, чтобы программно получить доступ к объекту с именем «InnerEllipse».

Я стараюсь делать это с помощью следующей строки кода:

Ellipse InnerEllipse = (Ellipse) this.Template.FindName("InnerEllipse", this); 

, который называется в собственности под названием «Цвет» внутри класса в «ControlButton»:

public Color Color 
{ 
    set 
    { 
     Ellipse InnerEllipse = (Ellipse)this.Template.FindName("InnerEllipse", this); 
    } 
} 

свойство «Цвет 'затем инициализируется, когда я использую «UserControl»

<Controlli:ControlButton Height="169" Width="119" Color="DarkGreen"/> 

проблема в том, что функция «FindName» возвращает мне «null». Я не могу понять, чего не хватает. Большое спасибо!

+0

Вы пробовали this.FindName («InnerEllipse», this.Template)? – Dbl

ответ

0

Проблема заключается в том, что свойство Color установлено до.

Color должно быть зависимым имуществом. Затем можно указать значение по умолчанию, а также подключение к PropertyChangedCallback, которая вызывается всякий раз, когда она изменяется:

public partial class ControlButton : UserControl 
{ 
    public ControlButton() 
    { 
     InitializeComponent(); 
    } 

    Ellipse InnerEllipse; 
    public override void OnApplyTemplate() 
    { 
     base.OnApplyTemplate(); 
     InnerEllipse = (Ellipse)this.Template.FindName("InnerEllipse", this); 
    } 

    public static readonly DependencyProperty ColorProperty = 
     DependencyProperty.Register("Color", typeof(Color), 
     typeof(ControlButton), new FrameworkPropertyMetadata(Colors.DarkGreen, new PropertyChangedCallback(OnColorChanged))); 

    public Color Color 
    { 
     get { return (Color)GetValue(ColorProperty); } 
     set { SetValue(ColorProperty, value); } 
    } 

    private static void OnColorChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) 
    { 
     ControlButton ctrl = d as ControlButton; 
     if (ctrl.InnerEllipse != null) 
      ctrl.InnerEllipse.Fill = new SolidColorBrush() { Color = ctrl.Color }; 
    } 
} 
+0

Я использовал «OnApplyTemplate()», чтобы получить объект «InnerEllipse» и делать все, что мне нужно, чтобы делать внутри этой функции. Спасибо! – Enrico

Смежные вопросы