C# 将相同的动态样式应用于栅格中相同类型的所有图元
我有一个充满标签的网格,所有标签都使用相同的样式,即DynamicSource:C# 将相同的动态样式应用于栅格中相同类型的所有图元,c#,wpf,styling,dynamicresource,C#,Wpf,Styling,Dynamicresource,我有一个充满标签的网格,所有标签都使用相同的样式,即DynamicSource: <Label Grid.Row="0" Style="{DynamicResource MyStyle}"/> <Label Grid.Row="1" Style="{DynamicResource MyStyle}"/> <Label Grid.Row="2" Style="{DynamicResource MyStyle}"/> 有没有办法只为网格中的所有标签设置一次样
<Label Grid.Row="0" Style="{DynamicResource MyStyle}"/>
<Label Grid.Row="1" Style="{DynamicResource MyStyle}"/>
<Label Grid.Row="2" Style="{DynamicResource MyStyle}"/>
有没有办法只为网格中的所有标签设置一次样式?我试过了,但是
BasedOn
不适用于DynamicResources
您可以执行以下操作:
<Window.Resources>
<Style TargetType="Label">
...
</Style>
</Window.Resources>
...
一种方法是使用合并词典
如下:
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/assemblyName;component/yourStyle.xaml"/>
</ResourceDictionary.MergedDictionaries>
<!--If you want to include additional resources you need to place them here-->
<SolidColorBrush x:Key="TextBox.Static.Border" Color="#FFABAdB3"/>
</ResourceDictionary>
</UserControl.Resources>
<Grid>
<Grid.Resources><!-- This will only use the style in the Grid-->
<Style TargetType="Label" BasedOn="{StaticResource MyStyle}"/>
</Grid.Resources>
</Grid>
然后在网格中,您可以这样使用它:
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/assemblyName;component/yourStyle.xaml"/>
</ResourceDictionary.MergedDictionaries>
<!--If you want to include additional resources you need to place them here-->
<SolidColorBrush x:Key="TextBox.Static.Border" Color="#FFABAdB3"/>
</ResourceDictionary>
</UserControl.Resources>
<Grid>
<Grid.Resources><!-- This will only use the style in the Grid-->
<Style TargetType="Label" BasedOn="{StaticResource MyStyle}"/>
</Grid.Resources>
</Grid>
现在应该只对网格或
标签使用您的样式,其中Style=“{StaticResource myStyle}”
在UC
或窗口中包含字典,然后将其称为StaticResource
,或者设置标签的样式,如so。code
@XAMlMAX:您是指我的App.xaml中的MergedDictionary?我怎么把它放在我的UC中?我用什么来代替三个点?你在“MyStyle”中做的样式。样式在另一个集合中。这很有效。另外,似乎在App.xaml中使用MergedDictionary而不是UserControl就足够了。这有什么副作用吗?@gartenriese说实话,我从来没有试过,而且从我所知道的情况来看,你的exe和UC在一个单独的程序集中。您使用的是什么VS?我使用的是来自不同程序集的样式,但是App.xaml和UserControl在同一个项目中。我正在使用VS2013。现在,如果您的UC
位于不同的程序集中,那么exe
将无法工作。关于包含来自不同程序集的样式,这没有任何区别,因为WPF使用URI,您可以引用其中的程序集,就像我在回答中指出的那样@吊袜带