5

プロジェクトのすべてのユーザー コントロールの背景プロパティを設定したいと考えています。

で試しました

<style TargetType={x:Type UserControl}>
    <setter property="Background" Value="Red" />
</style>

コンパイルされますが、動作しませんでした。

何か案が?ありがとう!

4

2 に答える 2

23

スタイルを特定のクラスにのみ設定できるため、これは機能します (UserControl オブジェクトを作成しますが、あまり役に立ちません)。

<Window.Resources>
    <Style TargetType="{x:Type UserControl}">
        <Setter Property="Background" Value="Red" />
    </Style>
</Window.Resources>
<Grid>
    <UserControl Name="control" Content="content"></UserControl>
</Grid>

しかし、これはそうではありません (UserControl から派生したクラスを作成します):

<Window.Resources>
    <Style TargetType="{x:Type UserControl}">
        <Setter Property="Background" Value="Red" />
    </Style>
</Window.Resources>
<Grid>
    <l:MyUserControl Name="control" Content="content"></l:MyUserControl>
</Grid>

できることは、Style プロパティを使用してスタイルを明示的に設定することです。

<Window.Resources>
    <Style TargetType="{x:Type UserControl}" x:Key="UCStyle">
        <Setter Property="Background" Value="Red" />
    </Style>
</Window.Resources>
<Grid>
    <l:MyUserControl Name="control" Content="content" Style="{StaticResource UCStyle}"></l:MyUserControl>
</Grid>

または派生クラスごとにスタイルを作成する場合、BasedOn を使用してスタイル コンテンツの重複を避けることができます。

<Window.Resources>
    <Style TargetType="{x:Type UserControl}" x:Key="UCStyle">
        <Setter Property="Background" Value="Red" />
    </Style>
    <Style TargetType="{x:Type l:MyUserControl}" BasedOn="{StaticResource UCStyle}" />
</Window.Resources>
<Grid>
    <l:MyUserControl Name="control" Content="content"></l:MyUserControl>
</Grid>
于 2009-03-11T10:38:57.117 に答える