2011-08-10 150 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