首页 > 解决方案 > 无法访问嵌套 WPF 样式的样式

问题描述

我已经概括了我的表格,并为每种类型的表格设计了一般样式:

 <Style TargetType="UserControl" x:Key="ViewForm">
     <Setter Property="Padding" Value="18"></Setter>
     <Style.Resources>
         <Style TargetType="TextBlock">
             <Setter Property="FontFamily" Value="{StaticResource IranSans}"/>
             // ...
         </Style>

         <Style TargetType="TextBlock" x:Key="Right">
             <Setter Property="FontFamily" Value="{StaticResource IranSans}"/>
         </Style>

         <Style TargetType="TextBlock" x:Key="Left">
             <Setter Property="FontFamily" Value="{StaticResource IranSans}"></Setter>
             // ...
         </Style>

         <Style TargetType="Label">
             <Setter Property="FontFamily" Value="{StaticResource IranSans}"/>
             // ...
         </Style>
     </Style.Resources>
 </Style>

我正在使用它,我UserControls希望能够为我的 s 使用LeftRight样式,TextBlock但我无法访问它们。例如:

 <TextBlock Grid.Row="3" Style="{StaticResource Right}">Email :</TextBlock>

*** 对于那些没有的风格,一切都很好x:Key="SomeKey..."

我该怎么办 ?

标签: c#wpfstyles

解决方案


用户控件“资源”和用户控件“样式资源”是两个不同的东西。用户控件的嵌套控件(如文本框、标签)可以访问“资源”而不是“样式资源”。

所以正确的方法是 -

<UserControl>
<UserControl.Resources>
  <!-- Place all styles that you want to put over child controls -->
</UserControl.Resources>
<UserControl.Style>
  <Style>
        <Style.Resources>
             <!-- Place all styles that you want to use within this style -->
        </Style.Resources>
   </Style>
</UserControl.Style>
</UserControl>

推荐阅读