【问题标题】:Creating Custom Silverlight Control创建自定义 Silverlight 控件
【发布时间】:2011-08-11 05:07:43
【问题描述】:

我们正在尝试创建一个自定义控件,该控件包含绑定到它的列表中的每个项目的文本框的包裹部分。

像这样:

<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 变成自定义控件?

谢谢!

【问题讨论】:

    标签: silverlight xaml


    【解决方案1】:

    你想做的,不需要自定义控件,一个样式就够了:

    <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. 如果没有 Themes 文件夹,请将其添加到项目的根目录,并在 Themes 文件夹中创建一个名为 Generic.xaml 的新 ResourceDictionary 文件。
    3. 创建一个新类,从 ItemsControl 继承(我们称之为 MyItemsControl)。
    4. 像这样添加一个构造函数:

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

    5. 将上述样式添加到 Generic.xaml 文件中,删除 x:Key 属性并将 TargetType 更改为 MyItemsControl(您需要为本地命名空间添加 xmlns 定义)。
    6. 现在回到您的客户项目,引用 Control Library 项目。
    7. 在相应的 Page\UserControl xaml 文件中添加 xmlns 定义,并将 MyItemsControl 用作任何其他 ItemsControl。

    【讨论】:

    • 嗯,这是一个出于演示原因的简单示例。我想覆盖 OnItemsSourceChanged 并将各种点击事件包含在一个类中,我可以在整个项目中使用。
    • 我以为是这样。按照列出的步骤进行操作,如果您需要特殊物品,请不要忘记覆盖 IsItemItsOwnContainerOverrideGetContainerForItemOverride 方法 - 每次都找我
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-06
    • 2012-05-25
    相关资源
    最近更新 更多