2011-08-10 102 views
0

我们正在试图制作一个自定义控件,其中包含绑定到列表中的每个项目的文本框的一个包装部分。创建自定义Silverlight控件

像这样:

<ItemsControl x:Name="asdf"> 
<ItemsControl.ItemsPanel> 
    <ItemsPanelTemplate> 
    <controls:WrapPanel /> 
    </ItemsPanelTemplate> 
</ItemsControl.ItemsPanel> 
<ItemsControl.ItemTemplate> 
    <DataTemplate> 
    <TextBox Text="{Binding}" /> 
    </DataTemplate> 
</ItemsControl.ItemTemplate> 
</ItemsControl> 

但是,我们把它变成一个自定义的控制时,它不设置ItemsPanel到WrapPanel,也没有做任何的ItemTemplate:

<ItemsControl x:Class="SilverlightApplication1.PillTagBox" 
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:controls= "clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Toolkit"> 

<ItemsControl.ItemsPanel> 
    <ItemsPanelTemplate> 
    <controls:WrapPanel /> 
    </ItemsPanelTemplate> 
</ItemsControl.ItemsPanel> 
<ItemsControl.ItemTemplate> 
    <DataTemplate> 
    <TextBox Text="{Binding}" /> 
    </DataTemplate> 
</ItemsControl.ItemTemplate> 

</ItemsControl> 

这只是表明项目的绑定列表一样,没有造型可言:

<ItemsControl x:Name="asdf" /> 

我们如何做第一大块XAML进入自定义控件?

谢谢!

回答

2

对于你想做什么,你并不需要一个自定义的控制,一种风格是不够的:

<Style x:Key="MyControlStyle" TargetType="ItemsControl"> 
    <Setter Property="ItemsPanel"> 
     <Setter.Value> 
      <ItemsPanelTemplate> 
       <controls:WrapPanel/> 
      </ItemsPanelTemplate> 
     </Setter.Value> 
    </Setter> 
    <Setter Property="ItemTemplate"> 
     <Setter.Value> 
      <DataTemplate> 
       <TextBox Text="{Binding}" /> 
      </DataTemplate> 
     </Setter.Value> 
    </Setter> 
</Style> 

,然后在实例:

<ItemsControl x:Name="asdf" Style="{StaticResource MyControlStyle}" /> 

如果你确实需要一个自定义控件由于其他原因:

  1. 使用Silverlight控件库模板创建一个新项目(所有定义都在此项目中)。
  2. 如果没有主题文件夹,请将其添加到项目的根目录,并在主题文件夹中创建一个名为Generic.xaml的新ResourceDictionary文件。
  3. 创建一个新的类,从ItemsControl继承(让我们称之为MyItemsControl)。
  4. 添加这样的构造:

    public MyItemsControl() { this.DefaultStyleKey = typeof(MyItemsControl); }

  5. 添加风格上面的Generic.xaml文件,删除X:主要属性,改变的TargetType到MyItemsControl(你需要添加本地名称空间的xmlns定义)。
  6. 现在回到您的客户项目,参考Control Library项目。
  7. 在相应的Page \ UserControl xaml文件中添加xmlns定义,并使用MyItemsControl作为任何其他ItemsControl。
+0

那么,这是一个简单的例子,因为演示的原因。我想重写OnItemsSourceChanged,并在我的项目中可以使用的一个类中包含各种点击事件。 –

+0

我以为是这样。按照列出的步骤,如果您需要特殊项目,请不要忘记重写'IsItemItsOwnContainerOverride'和'GetContainerForItemOverride'方法 - 每次都会收到我 – XAMeLi