2010-12-29 9 views
2

내 UserControl에는 여러 개의 레이블이 있습니다. XAML에서 나는 클라이언트가 이들 모두를 위해 Foreground를 한 번에 설정할 수있는 설정기를 정의하려고합니다.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> 

코드 뒤에 : 당신이 값이있는 UserControl의 사용자가 외부 적으로 설정 될 수 있도록하려면

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, 수 다음 컨트롤의 모든 인스턴스에 설정할 수 있습니다.

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); } 
} 
당신은이 값에 바인딩 UserControl을 내부 라벨의 기본 스타일을 만들 수 있습니다

:

<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> 

다음 자체에 적용되는 고유의 값을 설정할 수있는 컨트롤의 인스턴스 레이블 :

<MyUserControl LabelForeground="Red"/> 
관련 문제