自定义商量类库模板查找控件无法找到
我通过sl类库,自定义了一个控件,里面定义了一个属性和模板ControlTemplate,但是如果在xaml页面上直接给这个属性复制的话,就会报“找不到控件Logo”的错误。
模板如下:
<Style TargetType="local:myUI">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:myUI">
<Grid x:Name="root" Background="Black">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Border>
<MediaElement/>
</Border>
<Image x:Name="Logo"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
想要着的就是Logo这个Image控件。
自定义的属性是LogoUri,代码如下:
private string logouri= "";
public string LogoUri
{
get { return (string)GetValue(LogoUriProperty); }
set { SetValue(LogoUriProperty, value); }
}
public static readonly System.Windows.DependencyProperty LogoUriProperty =
System.Windows.DependencyProperty.Register("LogoUri", typeof(string), typeof(myUI),
new System.Windows.PropertyMetadata("", new System.Windows.PropertyChangedCallback(LogoUriChanged)));
private static void LogoUriChanged(System.Windows.DependencyObject d, System.Windows.DependencyPropertyChangedEventArgs e)
{
((myUI)d).LogoUriChanged(e);
}
protected virtual void LogoUriChanged(System.Windows.DependencyPropertyChangedEventArgs e)
{
logouri= (string)e.NewValue;
setlogouri(); //这里是一个设置logo的方法
}
查找控件的代码:
base.GetTemplateChild("logo")
这个方法总是返回null,就是没有找到Image控件。
前台引用的时候是这样的:
<UserControl x:Class="MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:u="clr-namespace:ui;assembly=ui"
>
<Grid x:Name="LayoutRoot" Background="Black">
<Border BorderThickness="1" BorderBrush="Red" Width="500" Height="500">
<u:myUI logoUri="http://localhost:8080/img/logo.png"/>
</Border>
</Grid>
</UserControl>
查资料后觉得是这个时候还没有应用模板的原因造成的,所以找不到任何的控件,不知道理解错了没有?
如果是这样的话,那应该怎么解决这个错误呀?能不能提供以下思路?
如果不是这个原因的话,那是什么问题?