Wpf 使用XAML为UserControl中的所有元素添加前景色设置器
My UserControl包含许多标签。在XAML中,我想定义一个setter,它允许客户端一次为所有这些设置前台Wpf 使用XAML为UserControl中的所有元素添加前景色设置器,wpf,xaml,user-controls,Wpf,Xaml,User Controls,My UserControl包含许多标签。在XAML中,我想定义一个setter,它允许客户端一次为所有这些设置前台 源代码:(简化) 在第页资源下: <DataTemplate x:Key="customItemTemplate"> <StackPanel Orientation="Horizontal"> <MyControlLib:XYControl Unit="{Binding XYUnit}"/> &
源代码:(简化) 在第页资源下:
<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>
(阅读XAML对我想要实现的WPF伟大性的评论)
当然,customItemTemplate
在页面中的多个位置使用不同的颜色
在WPF中,它是多么简单 我相信这个例子会对你有所帮助。 样式是在父节点中定义的,因此它在所有标签上生效,并且在代码中它将被新样式替换 XAML:
如果希望UserControl的用户能够在外部设置该值,则可以定义新的
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"/>
<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"/>