1

WPF の質問です。何をグーグルで検索すればよいかわかりません。

私はユーザーコントロールを持っています:

<UserControl x:Class="MyProj.MyControl"
             x:Name="Self"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Button />
</UserControl>

私はこのように使用します:

<local:MyControl Background="Green" />

でも、背景は変わらないようです。ボタンの背景が変わっていないからです。ボタンの背景にユーザーコントロールの背景を使用したい。

私はこれを行うことができると思います:

<UserControl x:Class="MyProj.MyControl"
             x:Name="Self"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Button Background="{Binding Path=Background, ElementName=Self" />
</UserControl>

しかし、Control および ContentControl から継承されたすべてのプロパティ (ToolTip、BorderThickness、BorderBrush など) をボタンに適用したいと考えています。

それで、これの代わりに何ができますか:

<UserControl x:Class="MyProj.MyControl"
             x:Name="Self"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Button Background="{Binding Path=Background, ElementName=Self"
            ToolTip="{Binding Path=ToolTip, ElementName=Self"
            BorderThickness="{Binding Path=BorderThickness, ElementName=Self"
            BorderBrush="{Binding Path=BorderBrush, ElementName=Self"
            ...
            ...
            ...
            ... />
</UserControl>

?

(注: これは、多くのコントロールをホストする大きな UserControl の小さな (実際、私が管理できる最小の) 例です。)

4

1 に答える 1

1

うーん。簡単に言えば、できません。少なくとも簡単にはできません。XAML は、HTML/CSS のようには機能しません。(さらにButton言えば、ほとんどすべてのControl) は、既定ではコンテナーからプロパティを継承しません。

継承する独自の などのコントロールを作成することもできButtonます...代わりに、Styleすべてに適用され、含まれる要素のプロパティを取得しようとする を宣言することもできます(つまり、 を介してRelativeSource FindAncestor)...または、あなたがしたことをすることができますここでやっている:すべてのプロパティを手動で設定します。

Styleアプローチの例:

<Style TargetType="{x:Type Control}">
    <Setter 
        Property="Background" 
        Value="{Binding (Control.Background), RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Control}}}"/>
</Style>
于 2013-01-03T17:25:15.750 に答える