【问题标题】:ItemContainerStyle in Custom Control Derived From ListBox从 ListBox 派生的自定义控件中的 ItemContainerStyle
【发布时间】:2009-12-09 16:24:35
【问题描述】:

Silverlight 设计师大师请多多包涵,这很复杂(对我来说)。

我正在创建一个从 Silverlight 3.0 列表框派生的自定义控件。为了不显示大量代码(最初),让我描述一下设置。

我有一个类库,其中包含一个用于我的控制逻辑的类。然后我有一个包含样式细节的 Themes/generic.xaml。在 generic.xaml 中,我有一个定义默认布局的样式,并查找我正在为 Template、ItemsPanel 和 ItemTemplate 设置值的 ListBox。

在我的测试应用程序中,我将控件添加到 MainPage.xaml 并运行它,它运行良好。我将数据动态绑定到我的控件,效果很好。

现在我想为我的派生控件设置 ItemContainerStyle。如果我在 MainPage.xaml 文件中创建样式并将 ItemContainerStyle 属性设置为该控件,如下所示:

<dti:myControl x:Name="MyControl1" ItemContainerStyle="{StaticResource MyListBoxItem}"
                                  Height="500" 
                                  Width="200" 
                                  Margin="10"
                                  Background="AliceBlue"
                                  />

它按预期工作。

但是,我想在类库中执行此操作,或者更具体地说,在 generic.xaml 中执行此操作。我尝试将此 Setter 设置为我当前的样式:

<Setter Property="ItemContainerStyle">
  <Setter.Value>
    <ControlTemplate>
      <Grid Background="Red" Margin="3">
        <ContentPresenter x:Name="contentPresenter"
          ContentTemplate="{TemplateBinding ContentTemplate}"
            HorizontalAlignment="Stretch" Margin="3"/>
      </Grid>
    </ControlTemplate>
  </Setter.Value>
</Setter>

它惨遭失败:

“System.ArgumentException: 'System.Windows.Controls.ControlTemplate' 不是属性 'ItemContainerStyle' 的有效值。”

注意:这不是我想用于 ItemContainerStyle 的实际样式。我实际上希望在此处为 ListBoxItem 的各种选定/未选定状态插入一些 VSM(用于动态绑定控件)。

所以,问题是如何将 ItemContainterStyle 应用到我的自定义控件,当它使用 generic.xaml 定义时?当我以后实际使用该控件时,我不希望设置该属性。

谢谢,

美丽

【问题讨论】:

  • 你遗漏了重要的一点:MyListBoxItem 资源的内容

标签: silverlight xaml silverlight-3.0 listbox custom-controls


【解决方案1】:

您错过了将 Style 标签放入您的 Setter.Value 中。 ItemContainerstyle 将 Style 期望为 ListBoxItem(除非您将 ListBoxItem 子类化为您自己的派生版本。)

<Setter Property="ItemContainerStyle"> 
   <Setter.Value>  
    <Style TargetType=”{x:Type ListBoxItem}“ >
      <Setter Property="Template">
        <Setter.Value>            
            <ControlTemplate> 
          <Grid Background="Red" Margin="3">        
              <ContentPresenter x:Name="contentPresenter" ContentTemplate="{TemplateBinding ContentTemplate}" HorizontalAlignment="Stretch" Margin="3"/> 
         </Grid> 
     </ControlTemplate>
    <Setter.Value>
    </Style>
 </Setter.Value> 

【讨论】:

  • +1 虽然我不确定 x:Type 在 Silverlight 中是否有效,但 TargetType="ListBoxItem" 就足够了。
  • 如果我结合 Jobi 和 Anthony 的答案,这将有效。多谢你们。我已经为这个发疯了太多小时了!
猜你喜欢
  • 2016-07-19
  • 1970-01-01
  • 2012-08-17
  • 1970-01-01
  • 2012-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多