【问题标题】:Apply same dynamic style to all elements of same kind in grid对网格中所有同类元素应用相同的动态样式
【发布时间】:2016-05-24 15:18:30
【问题描述】:

我有一个充满标签的网格,它们都使用相同的样式,即 DynamicResource:

<Label Grid.Row="0" Style="{DynamicResource MyStyle}"/>
<Label Grid.Row="1" Style="{DynamicResource MyStyle}"/>
<Label Grid.Row="2" Style="{DynamicResource MyStyle}"/>

有没有办法只为网格中的所有标签设置一次样式?我试过this way,但是BasedOn 不适用于DynamicResources

【问题讨论】:

  • 在您的UCWindow 中包含字典,然后将其称为StaticResource,或者像&lt;Style TargetType="{x:Type Label}"&gt;..code&lt;/Style&gt; 那样设置标签的样式。
  • @XAMlMAX:您的意思是我的 App.xaml 中的 MergedDictionary?我如何把它放在我的 UC 中?

标签: c# wpf styling dynamicresource


【解决方案1】:

一种方法是像这样使用MergedDictionaries

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

现在应该只将您的样式用于网格或Label where Style="{StaticResource myStyle}"

【讨论】:

  • 这行得通。此外,似乎在 App.xaml 中有 MergedDictionary 而不是 UserControl 就足够了。有没有副作用?
  • @gartenriese 老实说,我从未尝试过,据我所知,您的 exe 和您的 UC 位于单独的程序集中。你用的是什么VS?
  • 我正在使用来自不同程序集的样式,但是 App.xaml 和 UserControl 在同一个项目中。我正在使用 VS2013。
  • 你去吧,如果你的 UCexe 在不同的程序集中,那么它就行不通了。关于包含来自不同程序集的样式,它没有任何区别,因为 WPF 使用 URI,您可以只引用其中的程序集,就像我在回答中指出的那样。 @gartenriese
【解决方案2】:

你可以这样做:

    <Window.Resources>

    <Style TargetType="Label">

    ...

    </Style>

    </Window.Resources>

【讨论】:

  • 我用什么代替三个点?
  • 你在“MyStyle”中所做的样式。
  • 样式在另一个程序集中。
猜你喜欢
  • 2017-10-30
  • 1970-01-01
  • 1970-01-01
  • 2020-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多