WPF:按键寻址嵌套样式

sdnqo3pr  于 2022-11-18  发布在  其他
关注(0)|答案(1)|浏览(159)

我有一个相当复杂的WPF UserControl,它需要很多自定义样式,并且同一控件类型需要几种不同的样式。

我希望使用嵌套样式(使用Style.Resources)作为一种命名空间机制,如下所示:

使用者控件范例:

  1. <UserControl Style="{StaticResource AwesomeControl}>
  2. <Grid>
  3. <Button Style="{StaticResource ButtonA}"/>
  4. <Button Style="{StaticResource ButtonB}"/>
  5. </Grid>
  6. </UserControl>

我 * 希望 * 如何定义我的风格:

  1. <ResourceDictionary>
  2. <Style TargetType="UserControl" x:Key="AwesomeControl">
  3. <Style.Resources>
  4. <Style TargetType="Button" x:Key="ButtonA"> </Style>
  5. <Style TargetType="Button" x:Key="ButtonB"> </Style>
  6. </Style.Resources>
  7. </Style>
  8. </ResourceDictionary>

然而,这并不起作用。据我所知,似乎不可能通过它们的键来处理嵌套样式。(我已经搜索了很多,但没有找到一个这样做的例子。)
我可以通过删除样式的嵌套来使它更容易工作,使它们都保持在顶层。但是,我必须将它们的键更改为AwesomeControlButtonA等,以将它们与应用程序的其他部分区分开来
我觉得这不太理想。
所以我的问题是:

我正在尝试的上面的代码是否可行?如果不可行,是否有其他的命名空间方法可以用来防止像AwesomeControlButtonA这样的笨拙键?

fd3cxomn

fd3cxomn1#

也许DynamicResource可以解决你的问题

  1. <Grid>
  2. <Button Style="{DynamicResource ButtonA}"/>
  3. <Button Style="{DynamicResource ButtonB}"/>
  4. </Grid>

在上下文中:

  1. <Grid>
  2. <Grid.Resources>
  3. <Style x:Key="AW" TargetType="UserControl">
  4. <Style.Resources>
  5. <Style TargetType="Button" x:Key="AB">
  6. <Setter Property="Background" Value="Red" />
  7. </Style>
  8. <Style TargetType="Button" x:Key="BB">
  9. <Setter Property="Background" Value="Yellow" />
  10. </Style>
  11. </Style.Resources>
  12. </Style>
  13. <Style x:Key="AR" TargetType="UserControl">
  14. <Style.Resources>
  15. <Style TargetType="Button" x:Key="AB">
  16. <Setter Property="Background" Value="Green" />
  17. </Style>
  18. <Style TargetType="Button" x:Key="BB">
  19. <Setter Property="Background" Value="Blue" />
  20. </Style>
  21. </Style.Resources>
  22. </Style>
  23. </Grid.Resources>
  24. <StackPanel>
  25. <UserControl Style="{StaticResource AW}">
  26. <StackPanel>
  27. <Button Content="A" Style="{DynamicResource AB}" />
  28. <Button Content="A" Style="{DynamicResource BB}" />
  29. </StackPanel>
  30. </UserControl>
  31. <UserControl Style="{StaticResource AR}">
  32. <StackPanel>
  33. <Button Content="A" Style="{DynamicResource AB}" />
  34. <Button Content="A" Style="{DynamicResource BB}" />
  35. </StackPanel>
  36. </UserControl>
  37. </StackPanel>
  38. </Grid>

展开查看全部

相关问题