2010-12-18 90 views
0

我已经在我的资源文件中定义的样式像下面Silverlight的列表框自定义样式

<Style x:Name="ListBoxStyle" TargetType="ListBox" > 
    <Setter Property="Template"> 
     <Setter.Value> 
      <ControlTemplate TargetType="ListBox">      
       <StackPanel Orientation="Horizontal"> 
        <TextBlock Text="{Binding Name,Mode=TwoWay}" 
           Margin="5" 
           Foreground="Red"> 
        </TextBlock> 
        <TextBlock Text="{Binding Age,Mode=TwoWay}" 
           Margin="5"> 
        </TextBlock> 
       </StackPanel> 
      </ControlTemplate> 
     </Setter.Value> 
    </Setter>  
</Style> 

我很茫然,什么把这里的数据模板

<ListBox x:Name="MyList" ItemsSource="{Binding }"> 
    <ListBox.ItemTemplate> 
     <DataTemplate> 
     </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox> 

我尝试使用内

<ContentPresenter Style="{StaticResource ListBoxStyle}"></ContentPresenter> 

甚至

<ContentControl Style="{StaticResource ListBoxStyle}"></ContentControl>` 

,但得到这个错误

无法分配财产 'System.Windows.FrameworkElement.Style'。

如果我想提供自定义样式,请在DataTemplate标记之间插入什么?

+0

你想完成什么?您已经为ListBox定义了一种样式,并且您正试图将其应用于ContentPresenter和ContentControl。那是不对的。 – decyclone 2010-12-18 09:10:41

+0

我想在另一个资源文件中定义列表框的样式,并在我的page.xaml中指定该样式。什么是正确的方式? – user20358 2010-12-18 10:13:07

回答

0

尝试:

<ListBox x:Name="MyList" ItemsSource="{Binding }"> 
    <ListBox.ItemTemplate> 
     <DataTemplate> 
<StackPanel Orientation="Horizontal"> 
        <TextBlock Text="{Binding Name,Mode=TwoWay}" 
           Margin="5" 
           Foreground="Red"> 
        </TextBlock> 
        <TextBlock Text="{Binding Age,Mode=TwoWay}" 
           Margin="5"> 
        </TextBlock> 
       </StackPanel> 
     </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox> 

这shpuld解决您的问题。

如果您定义样式,您可以定义ListBox的外观(背景,前景...)。 您可以在此处获得默认样式:http://msdn.microsoft.com/en-us/library/cc278062(v = vs.95).aspx

ItemTemplate(它是一个DataTemplate)定义,如何列表中单个元素的数据表示看起来像(您使用绑定等等......)。

如果您想为单个元素(如MouseOver,Focussed)定义样式,请为ListBoxItems编写样式。您可以通过ItemContainerStyle将其添加到列表框中。

<ListBox ItemContainerStyle="{StaticResource YourResourceKey}"/>