【发布时间】:2011-07-25 10:23:18
【问题描述】:
我目前正在处理一个小项目,但在使用 silverlight 自定义控件时遇到了一些问题。我正在尝试为照片库创建一个自定义 ScrollViewer(将包含小图像)。我遇到的问题是 Visual Studio 抛出以下错误:
无法创建 ScrollableImageViewer 的实例
有人可以提供一些关于可能是什么原因导致此错误的指针,并可能提供一些解决方法吗?
下面是我编写的 XAML 和 C# 代码。
<navigation:Page x:Class="PWS.Views.Biography"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:PWS.Controls"
mc:Ignorable="d"
xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
d:DesignWidth="640" d:DesignHeight="480"
Title="This is the biography page">
<Grid x:Name="LayoutRoot">
<TextBlock x:Name ="tempText" FontSize="15" Foreground="Blue">this is the biography page</TextBlock>
<local:ScrollableImageViewer x:Name= "scrollableViewer" />
</Grid>
</navigation:Page>
我的自定义控件类名为ScrollableImageViewer,您可以在下面看到它的代码。
namespace PWS.Controls
{
[ContentProperty("Items")]
public class ScrollableImageViewer : Control
{
public static DependencyProperty ItemsProperty = DependencyProperty.RegisterAttached("Items", typeof(IList<UIElement>), typeof(ScrollableImageViewer), new PropertyMetadata(""));
public ScrollableImageViewer()
{
this.DefaultStyleKey = typeof(ScrollableImageViewer);
this.Items = new List<UIElement>();
}
public IList<UIElement> Items
{
get { return (IList<UIElement>)GetValue(ScrollableImageViewer.ItemsProperty); }
set { SetValue(ScrollableImageViewer.ItemsProperty, value); }
}
}
}
目前它非常简单,并且不包含用于滚动的自定义逻辑。
我必须添加的另一件事是包含此控件模板的 generic.xaml 文件。
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:PWS.Controls"
>
<Style TargetType="local:ScrollableImageViewer">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:ScrollableImageViewer">
<Grid Background="{TemplateBinding Background}">
<ScrollViewer x:Name="internalScrollViewer" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
Background="{TemplateBinding Background}"
VerticalScrollBarVisibility="Disabled"
HorizontalScrollBarVisibility="Hidden"
>
<StackPanel Background="{TemplateBinding Background}" FlowDirection="LeftToRight" IsHitTestVisible="False" Children="{TemplateBinding Items}"></StackPanel>
</ScrollViewer>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
从模板中可以看出,我希望我的控件包含一个内部 ScrollViewer 和一个 StackPanel,其 Children 属性应绑定到自定义控件的 Items 属性。
P.S 我在 SO 上进行了一些搜索,发现了一些关于类似问题的问题。其中大部分是通过在构造函数中添加代码来检查控件是否以设计器模式显示的来解决的,但这对我不起作用。看来我有不同的问题。
P.P.S我刚开始学习 Silverlight,所以如果你看到一些不好的代码,请随时指出来。
【问题讨论】:
标签: silverlight-4.0 c#-4.0 custom-controls