2010-12-29 5 views
2

私のUserControlには多数のラベルが含まれています。 XAMLでは、クライアントが一度にこれらのすべてのフォアグラウンドを設定できるようにするセッターを定義したいと思います。XAMLを使用して、UserControlのすべての要素の前景色にセッターを追加します。


ソースコード:(簡体字)Page.Resourcesの下

:ページの内容で

<DataTemplate x:Key="customItemTemplate"> 
    <StackPanel Orientation="Horizontal"> 
     <MyControlLib:XYControl Unit="{Binding XYUnit}"/> 
      <TextBlock Text="{Binding XYMultiplier}" Width="16"/> 
    </StackPanel> 
</DataTemplate> 

<ListBox x:Name="XYZList" ItemTemplate="{StaticResource customItemTemplate}"> 
    <!-- Set Foreground to "Red" for all items --> 
    <!-- For XYControl this is the TextForeground property --> 
    <!-- For TextBlock this is (naturally) the Foreground property --> 
</ListBox> 

(WPFのためのXAMLのコメントを読みます私が達成したい偉大さ)

もちろん、customItemTemplateは、ページの複数の場所で異なる色で使用されます。

WPFでどのくらい簡単にできますか。

答えて

1

私はこの例があなたを助けると信じています。 スタイルは親ノードで定義されているので、すべてのラベルに適用され、背後にあるコードでは新しいスタイルで置き換えられます。

XAML:

<StackPanel x:Name="root"> 
    <StackPanel.Resources> 
     <Style TargetType="Label"> 
      <Setter Property="Foreground" Value="Red"/> 
     </Style> 
    </StackPanel.Resources> 
    <Label>AAA</Label> 
    <Label>BBB</Label> 
    <Button Click="Button_Click">Change Color</Button> 
</StackPanel> 

コードの後ろに:あなたは値がユーザーコントロールのユーザーによって外部から設定することができるようにしたい場合は

private void Button_Click(object sender, RoutedEventArgs e) 
    { 
     var x = new Style(); 
     x.Setters.Add(new Setter { Property = TextBlock.ForegroundProperty, Value = new SolidColorBrush(Colors.Green) }); 

     root.Resources.Clear(); 
     root.Resources.Add(typeof(Label), x); 
    } 
2

は、あなたが定義することができ、新たなDependencyProperty、することができますコントロールの任意のインスタンスに設定します。

<UserControl.Resources> 
    <Style TargetType="{x:Type Label}"> 
     <Setter Property="Foreground" Value="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type MyUserControl}}, Path=LabelForeground}" /> 
    </Style> 
</UserControl.Resources> 

コントロールの任意のインスタンスは、その後、独自に適用される独自の値を設定することができます:あなたは、この値に結合し、ユーザーコントロール内のラベルのデフォルトスタイルを作成することができます

public static readonly DependencyProperty LabelForegroundProperty = DependencyProperty.Register(
    "LabelForeground", 
    typeof(Brush), 
    typeof(MyUserControl), 
    new UIPropertyMetadata(Brushes.Black)); 

public Brush LabelForeground 
{ 
    get { return (Brush)GetValue(LabelForegroundProperty); } 
    set { SetValue(LabelForegroundProperty, value); } 
} 

ラベル:

<MyUserControl LabelForeground="Red"/> 
関連する問題