2014-01-07 32 views
0

我的一个网格目前与下面的代码开始:WPF:移动面板资源字典文件

<Grid x:Name="Top_GRID" Margin="4.953,10" Width="817.28"> 
    <Grid.Resources> 
    <Style TargetType="TextBlock"> 
     <Setter Property="VerticalAlignment" Value="Center"/> 
     <Setter Property="Margin" Value="3"/> 
     <Setter Property="Background" Value="Red" /> 
    </Style> 
    <Style TargetType="TextBox"> 
     <Setter Property="VerticalAlignment" Value="Center"/> 
     <Setter Property="Margin" Value="3"/> 
    </Style> 
    <Style TargetType="Button"> 
     <Setter Property="VerticalAlignment" Value="Center"/> 
     <Setter Property="Margin" Value="3"/> 
    </Style> 
</Grid.Resources> 

只是为了澄清 - 我要声明一个电网其中所有的TextBlocks都具有背景属性设置为“红色”。全部按钮边距设置为“3”等。 我想将资源定义移动到字典文件。
我是否应该以某种方式将其包装为款式? 如果是这样,我将有一个递归样式声明(我认为是非法的)。
听起来很简单,但我找不到办法。

回答

1

试试这个

<Style x:Key="Grid_ControlStyle" TargetType="Grid"> 
     <Style.Resources>     
       <Style TargetType="TextBlock"> 
        <Setter Property="VerticalAlignment" Value="Center"/> 
        <Setter Property="Margin" Value="3"/> 
        <Setter Property="Background" Value="Red" /> 
       </Style> 
       <Style TargetType="TextBox"> 
        <Setter Property="VerticalAlignment" Value="Center"/> 
        <Setter Property="Margin" Value="3"/> 
       </Style> 
       <Style TargetType="Button"> 
        <Setter Property="VerticalAlignment" Value="Center"/> 
        <Setter Property="Margin" Value="3"/> 
       </Style>    
     </Style.Resources> 
    </Style> 
+0

正是我想要的! Tx – Shaul

+0

感谢您的评论! –

0

您需要在resourceDictionary文件中放置按钮,文本框等的所有样式。然后,在应用程序资源添加此文件:

<Application x:Class="Aplication.App" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     > 
<Application.Resources> 
    <ResourceDictionary> 
     <ResourceDictionary.MergedDictionaries> 
      <ResourceDictionary Source="Resources\YourResource.xaml"/> 
     </ResourceDictionary.MergedDictionaries> 
    </ResourceDictionary> 
</Application.Resources> 

然后在XAML中,你将能够使用它像这样

<TextBlock Grid.Column="1" Grid.Row="1" Text="bla bla" Style="{DynamicResource YourStyle}"/> 

最后你的风格应该像

<Style x:Key="StyleName" TargetType="{x:Type TextBlock}"> 
    <Setter Property="Margin" Value="3,3,3,3"/> 
    <Setter Property="FontFamily" Value="Arial"/> 
    <Setter Property="FontSize" Value="12pt"/> 
    <Setter Property="HorizontalAlignment" Value="Center"/> 
    <Setter Property="VerticalAlignment" Value="Center"/> 
</Style> 

希望这就是你在找什么。

+0

原始代码为网格元素声明了样式:“此网格中的所有TextBlocks都将被样式化......”。 您的解决方案要求我为每个控件设置样式,而不管它们在网格中的位置。 – Shaul

+0

@Shaul在这里你有一种风格,你可以用于你的应用程序中的所有文本块 – Sasha

0

请通过资源字典的WPF概念。任何风格,颜色,字体等等与您希望在应用程序的多个屏幕中重复使用的应用程序的外观有关的任何信息都将放置在资源字典中。

x:Key是可用于访问整个应用程序中任何位置样式的属性。 为了让您的资源字典通过应用程序可访问,请将其放置在其中app.xaml

+0

是的。您可以定义命名样式并稍后使用它们。 我想定义一个**默认的** Style,覆盖Grid下的元素。这有些不同。 – Shaul