0
我正嘗試創建自定義標籤雲控件。它應該工作的方式是用戶可以在itemsSource中給它一個字符串集合,並且轉換後的字符串將顯示在UI中。問題是,當我嘗試將控件放到應用程序中時出現以下錯誤:「無法創建類型爲TagCloudControl的實例」。誰能幫忙?WPF錯誤:無法在創建自定義控件時創建類型實例
代碼背後
public class TagCloudControl : ListBox
{
static TagCloudControl()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(TagCloudControl), new FrameworkPropertyMetadata
(typeof(TagCloudControl)));
}
//tags dependency property
public static DependencyProperty TagsProperty = DependencyProperty.Register("Tags",
typeof(IEnumerable<Tag>),
typeof(TagCloudControl));
public CollectionView GroupedTagsView { get; set; }
public TagCloudControl()
{
ItemsSource = Tags;
//group my tags by "name" property
GroupedTagsView = (ListCollectionView)CollectionViewSource.GetDefaultView(Tags);
GroupedTagsView.GroupDescriptions.Add(new PropertyGroupDescription("Name"));
}
public IEnumerable<Tag> Tags
{
get { return (IEnumerable<Tag>)GetValue(TagsProperty); }
set { SetValue(TagsProperty, value); }
}
}
XAML
<Window x:Class="TagCloudDemo.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:src="clr-namespace:TagCloudControlLibrary;assembly=TagCloudControlLibrary"
Title="Window1" Height="300" Width="300">
<Grid>
<src:TagCloudControl HorizontalAlignment="Center" VerticalAlignment="Center" Name="firstTag"/>
</Grid>
</Window>
TagControl XAML
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TagCloudControlLibrary">
<local:CountToBrushConverter x:Key="CountToBrushConverter"/>
<local:CountToFontSizeConverter x:Key="CountToFontSizeConverter"/>
<Style TargetType="{x:Type local:TagCloudControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:TagCloudControl}">
<Grid>
<WrapPanel Orientation="Horizontal"
Margin="2"
IsItemsHost="True">
</WrapPanel>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<DataTemplate x:Key="TagsTemplate">
<WrapPanel>
<TextBlock Text="{Binding Name}"
FontSize="{Binding ItemCount, Converter={StaticResource CountToBrushConverter}}"
Foreground="{Binding ItemCount, Converter={StaticResource CountToFontSizeConverter}}"/>
</WrapPanel>
</DataTemplate>
</ResourceDictionary>
標記類
public class Tag
{
public Tag(string name)
{
Name = name;
}
public string Name { get; set;}
}
啊我該怎麼做? – Ben 2011-03-02 22:06:23
謝謝,我得到了錯誤「一個新的表達式需要()後類型」 – Ben 2011-03-02 22:10:50
是的...我忘了()...我編輯更新。 (另外,你也想刪除'**')。它不能只是IEnumerable。它必須是一個實現IEnumerable的特定類型。 – Scott 2011-03-02 22:12:29