WPF后台设置xaml控件的样式System.Windows.Style

WPF后台设置xaml控件的样式System.Windows.Style

摘-自 :感谢 作者: IT小兵   http://3w.suchso.com/projecteac-tual/wpf-zhishi-houtai-shezhi-style.html

Style myStyle = (Style)this.FindResource("TabItemStyle");//TabItemStyle 这个样式是引用的资源文件中的样式名称

静态资源在第一次编译后即确定其对象或值,之后不能对其进行修改。动态资源则是在运行时决定,当运行过程中真正需要时,才到资源目标中查找其值。

比如:

  <Canvas Background="{DynamicResource innerLgbResource}">

StaticResources的适用场合:
(1)在资源第一次引用之后无需再修改资源的值。
(2)资源引用不会基于运行时的行为进行重新计算,比如在重新加载Page/Window的时候。
(3)当需要设置的属性不是DependencyObject或Freezable类型的时候,用StaticResource。
(4)当需要将资源编译到dll中,并打包为程序的一部份,或者希望在各应用程序之间共享时,也使用StaticResource。
(5)当需要为一个自定义控件创建一个Theme,并Theme中使用资源,就需要使用StaticResource。因为StaticResource的资源查找行为时可预测的,并且本身包含在Theme中。而对于DynamicResource,即使资源是定义在Theme中,也只能等到运行时确定,导致一些可能意料不到的情况发生。
(6)当需要使用资源设置大量的依赖属性(Dependency Property)的时候。
由于依赖属性具有属性系统提供的值缓存机制,所以,如果能在程序装载时设置依赖属性的值,这样,依赖属性就不需要检查自己的值并返回最后的有效值了。
 
Dynamic Resource一般使用在如下场合:
(1)资源的值依赖一些条件,而该条件直到运行时才能确定。
包括系统资源,或是用户可设置的资源。比如:可以创建引用系统属性诸如SystemColors,SystemFonts来设置值,而这些属性是动态的,它们的值又来自于运行环境和操作系统。
(2)为自定义控件引用或创建Theme Style。
(3)希望在程序运行期间调整资源字典的内容时。
(4)希望资源可以向前引用时(如上面在Canvas中引用innerLgbResource一样)
(5)资源文件很大,希望在运行时才加载。
(6)要创建的Style的值可能来自于其它值,而这些值又依赖于Theme或用户的设置。
(7)当引用资源的元素的父元素有可能在运行期改变,这个时候也需要使用动态资源。因为父元素的改变将导致资源查询的范围。

 

1、前台myWindow.xaml文件中的代码

 <TabControl x:Name="menuTab" Grid.RowSpan="2" Margin="0" Style="{DynamicResource TabControlStyle}" Grid.Row="1" Background="{x:Null}">
                <TabItem Header="系统设置" Height="83" Margin="80,0,0,0" Width="74" Style="{DynamicResource TabItemStyle}">
                    <TabItem.Background>
                        <ImageBrush ImageSource="skin/ico/ico_dsmain.png"/>  <!--这里图片需要替换才能正常运行-->
                    </TabItem.Background>
                    <Grid Background="{DynamicResource MyBrush}"/>
                </TabItem>
             </TabControl>

2、后台myWindow.xaml.cs文件中的代码

private void Button_Click(object sender, RoutedEventArgs e)
 {
            //动态添加子菜单
            TabItem myDnymicTab = new TabItem() { Header = "用户管理", Height = 83, Width = 74 }; 
            //设置图片
            ImageBrush myImageBrush=new ImageBrush(new BitmapImage(new Uri(@"../../skin/ico/ico_PluginCleaner.png", UriKind.Relative)));
            myDnymicTab.Background=myImageBrush;
            //设置位置
            Thickness myThickness =new Thickness(120,0,0,0);
            myDnymicTab.Margin=myThickness;
            //设置样式
            Style myStyle = (Style)this.FindResource("TabItemStyle");//TabItemStyle 这个样式是引用的资源文件中的样式名称
            myDnymicTab.Style = myStyle;
            //添加TabItem到TabControl中
            menuTab.Items.Add(myDnymicTab);
            menuTab.SelectedItem = myDnymicTab;
}

3、App.xaml中添加样式字典文件引用

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <!--App.xaml资源样式-->
            <ResourceDictionary Source="TabControlStyle.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

4、资源文件TabControlStyle.xaml中的样式:

<!-- 应该在此定义资源字典条目。-->
 <Style x:Key="TabControlStyle" TargetType="{x:Type TabControl}">
  <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
  <Setter Property="Padding" Value="4,4,4,4"/>
  <Setter Property="BorderThickness" Value="1"/>
  <Setter Property="BorderBrush" Value="{StaticResource TabControlNormalBorderBrush}"/>
  <Setter Property="Background" Value="#F9F9F9"/>
  <Setter Property="HorizontalContentAlignment" Value="Center"/>
  <Setter Property="VerticalContentAlignment" Value="Center"/>
  <Setter Property="Template">
   <Setter.Value>
    <ControlTemplate TargetType="{x:Type TabControl}">
     <Grid ClipToBounds="true" SnapsToDevicePixels="true" KeyboardNavigation.TabNavigation="Local">
      <Grid.ColumnDefinitions>
       <ColumnDefinition x:Name="ColumnDefinition0" Width="0.192*" />
       <ColumnDefinition x:Name="ColumnDefinition1" Width="0.808*"/>
      </Grid.ColumnDefinitions>
      <Border x:Name="ContentPanel" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Grid.Column="1" KeyboardNavigation.DirectionalNavigation="Contained" Grid.Row="0" KeyboardNavigation.TabIndex="2" KeyboardNavigation.TabNavigation="Local" Grid.ColumnSpan="1" Grid.RowSpan="1" Width="Auto" Margin="0">
       <ContentPresenter x:Name="PART_SelectedContentHost" ContentSource="SelectedContent" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" Width="Auto" Margin="0"/>
      </Border>
      <StackPanel x:Name="HeaderPanel" Margin="0" IsItemsHost="True">
       <StackPanel.Background>
        <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
         <GradientStop Color="#7AFFFFFF" Offset="0"/>
         <GradientStop Color="#42F0FCFF" Offset="1"/>
        </LinearGradientBrush>
       </StackPanel.Background>
      </StackPanel>
     </Grid>
     <ControlTemplate.Triggers>
      <Trigger Property="IsEnabled" Value="false">
       <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
      </Trigger>
     </ControlTemplate.Triggers>
    </ControlTemplate>
   </Setter.Value>
  </Setter>
 </Style>
<Style x:Key="TabItemStyle" TargetType="{x:Type TabItem}">
  <Setter Property="FocusVisualStyle" Value="{StaticResource TabItemFocusVisual}"/>
  <Setter Property="Foreground" Value="Black"/>
  <Setter Property="Padding" Value="6,1,6,1"/>
  <Setter Property="BorderBrush" Value="{StaticResource TabControlNormalBorderBrush}"/>
  <Setter Property="Background" Value="{StaticResource ButtonNormalBackground}"/>
  <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
  <Setter Property="VerticalContentAlignment" Value="Stretch"/>
  <Setter Property="Template">
   <Setter.Value>
    <ControlTemplate TargetType="{x:Type TabItem}">
     <Grid SnapsToDevicePixels="true">
      <Grid.RowDefinitions>
       <RowDefinition Height="0.69*"/>
       <RowDefinition Height="0.31*"/>
      </Grid.RowDefinitions>
      <Border x:Name="Bd" BorderThickness="0" CornerRadius="3" BorderBrush="Black" Margin="0" Grid.RowSpan="2" Visibility="Hidden">
       <Border.Background>
        <ImageBrush ImageSource="skin/ico/toolbar_pushed.png"/>
       </Border.Background>
      </Border>
      <Border x:Name="fg" BorderThickness="0" CornerRadius="3" BorderBrush="Black" Margin="0" Grid.RowSpan="2" Visibility="Hidden" RenderTransformOrigin="0.5,0.5">
       <Border.RenderTransform>
        <TransformGroup>
         <ScaleTransform/>
         <SkewTransform/>
         <RotateTransform/>
         <TranslateTransform/>
        </TransformGroup>
       </Border.RenderTransform>
       <Border.Background>
        <ImageBrush ImageSource="skin/ico/toolbar_hover.png"/>
       </Border.Background>
      </Border>
      <TextBlock Margin="0,0.333,0,3.833" TextWrapping="Wrap" VerticalAlignment="Stretch" d:LayoutOverrides="Height" Grid.Row="1" HorizontalAlignment="Center" Text="{TemplateBinding Header}" Foreground="White"/>
      <Border x:Name="ico" BorderThickness="0" CornerRadius="3" BorderBrush="Black" Margin="4,4,4.25,0" Grid.RowSpan="1" HorizontalAlignment="Center" VerticalAlignment="Center" Width="48" Height="48" Background="{TemplateBinding Background}" RenderTransformOrigin="0.5,0.5">
       <Border.RenderTransform>
        <TransformGroup>
         <ScaleTransform/>
         <SkewTransform/>
         <RotateTransform/>
         <TranslateTransform/>
        </TransformGroup>
       </Border.RenderTransform>
      </Border>
     </Grid>
     <ControlTemplate.Triggers>
      <Trigger Property="IsMouseOver" Value="true"/>
      <Trigger Property="IsSelected" Value="true">
       <Setter Property="Visibility" TargetName="Bd" Value="Visible"/>
       <Setter Property="Panel.ZIndex" TargetName="ico" Value="1"/>
      </Trigger>
      <MultiTrigger>
       <MultiTrigger.Conditions>
        <Condition Property="IsSelected" Value="false"/>
        <Condition Property="IsMouseOver" Value="true"/>
       </MultiTrigger.Conditions>
       <Setter Property="Visibility" TargetName="fg" Value="Visible"/>
       <Setter Property="RenderTransform" TargetName="ico">
        <Setter.Value>
         <TransformGroup>
          <ScaleTransform ScaleX="1.05" ScaleY="1.05"/>
          <SkewTransform/>
          <RotateTransform/>
          <TranslateTransform/>
         </TransformGroup>
        </Setter.Value>
       </Setter>
      </MultiTrigger>
      <Trigger Property="IsEnabled" Value="false"/>
     </ControlTemplate.Triggers>
    </ControlTemplate>
   </Setter.Value>
  </Setter>
 </Style>
posted @ 2015-08-28 17:51  黄文博  阅读(11796)  评论(0编辑  收藏  举报