0

我在我的资源文件中定义了一个样式,如下所示

   <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如果我想提供自定义样式,我应该在标签之间添加什么?

4

1 回答 1

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>

这应该可以解决您的问题。

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

ItemTemplate(它是一个 DataTemplate)定义了列表中单个元素的数据表示形式(您使用绑定等...)。

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

<ListBox ItemContainerStyle="{StaticResource YourResourceKey}"/>
于 2010-12-18T14:16:02.437 回答