ItemContainerStyle重写通用样式

时间:2011-01-05 22:39:54

标签: wpf itemscontrol itemcontainerstyle

我从我的App.xaml引用ExpressionDark.xaml,它工作正常,但是当我尝试在ItemsControl中使用ItemContainerStyle时,ItemsControl中的项目将恢复为基本样式。

<ItemsControl Grid.Column="1" VerticalAlignment="Center" Margin="10">
    <ItemsControl.ItemContainerStyle>
        <Style>
            <Setter Property="Margin" Value="5" />
        </Style>
    </ItemsControl.ItemContainerStyle>
    <ItemsControl.Items>
        <TextBlock Text="{Binding Error}" />
        <TextBox Text="{Binding Path=Username,UpdateSourceTrigger=PropertyChanged,ValidatesOnDataErrors=True}" Validation.ErrorTemplate="{StaticResource validationTemplate}"></TextBox>
        <TextBox Text="{Binding Path=Password,UpdateSourceTrigger=PropertyChanged,ValidatesOnDataErrors=True}" Validation.ErrorTemplate="{StaticResource validationTemplate}"></TextBox>
        <Button VerticalAlignment="Center" HorizontalAlignment="Right" Command="{Binding SignInCommand}" IsEnabled="{Binding CanSignIn}" Content="Sign In"></Button>
        <TextBox Text="{Binding Path=Username}"></TextBox>
    </ItemsControl.Items>
</ItemsControl>

我只是试图找到一个良好的垂直样式控件(很容易在项目之间添加边距),所以可能有更好的方式不会覆盖App.xaml中指定的样式。

TIA

2 个答案:

答案 0 :(得分:2)

如果您指定了&#34; &#34;风格,它被认为是一种全新的风格。 由于 ExpressionDark.xaml 的默认样式是该元素的forgotton。

要避免这种情况,您需要做的是:使用BasedOn =

参考基本样式
<ItemsControl.ItemContainerStyle>
   <Style BasedOn="{StaticResource Existing}">
      <Setter Property="Margin" Value="5" />
   </Style>
</ItemsControl.ItemContainerStyle>

为控件找到相应的默认样式。并使用 ExpressionDark.xaml 中的资源键替换Existing。您可以识别它,因为它将具有正确的TargetType属性集:

<Style TargetType="{x:Type ListBoxItem}"> x:Key=...

ListBoxItem是您正在使用的控件(待重新设计)

您可以考虑使用ListBox代替ItemsControl,因为它有ListBoxItem作为容器。

答案 1 :(得分:0)

他们使用保证金的方式很好,但是当您使用与App.xaml中的风格不同的风格时,它会不会使用App.xaml中的风格。

这是它在WPF中的工作方式,控件使用“最接近”的样式,并且由于您将此样式直接写入控件,因此它使用该样式。

您可以使用基于app.xaml的'BaseOn'属性在ExpressionDark.xaml中创建新样式,但您将添加:

<ItemsControl.ItemContainerStyle>
    <Style>
        <Setter Property="Margin" Value="5" />
    </Style>
</ItemsControl.ItemContainerStyle>