2014-01-20 45 views
2

我的任务是在每个StackPanel中嵌套20px的边距的每个Button上设置。在Silverlight而不是WPF中嵌套样式(如CSS)的吊坠

在WPF我使用这段代码Application.Resources:

<Style TargetType="StackPanel"> 
    <Style.Resources> 
    <Style TargetType="Button"> 
     <Setter Property="Margin" Value="20" /> 
    </Style> 
    </Style.Resources> 
</Style> 

在Silverlight中存在缺少 “Style.Resources” -Tag。但我试过这个代码:

<Style TargetType="StackPanel"> 
    <Setter Property="Resources"> 
    <Setter.Value> 
     <ResourceDictionary> 
      <Style TargetType="Button"> 
       <Setter Property="Margin" Value="20" /> 
      </Style> 
     </ResourceDictionary> 
    </Setter.Value> 
    </Setter> 
</Style> 

可悲的是在Silverlight方面没有任何事情发生(没有错误,没有结果)。

有没有人有一个想法,如果在Silverlight中,这种行为可能没有在每个Stackpanel manualy上设置Style by键?

回答

1

在Silverlight中,不能简单地完成什么,可以使用附加的依赖项属性来完成。 这是这样的属性,即做你想做的 - 将条目添加到元素ResourceDictionaries。

namespace SilverlightApplication1.Assets 
{ 
    public class Utils : DependencyObject 
    { 
     public static readonly DependencyProperty AdditionalResourcesProperty = DependencyProperty.RegisterAttached(
      "AdditionalResources", typeof(ResourceDictionary), typeof(Utils), new PropertyMetadata(null, OnAdditionalResourcesPropertyChanged)); 

     public static ResourceDictionary GetAdditionalResources(FrameworkElement obj) 
     { 
      return (ResourceDictionary)obj.GetValue(AdditionalResourcesProperty); 
     } 

     public static void SetAdditionalResources(FrameworkElement obj, ResourceDictionary value) 
     { 
      obj.SetValue(AdditionalResourcesProperty, value); 
     } 

     private static void OnAdditionalResourcesPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) 
     { 
      FrameworkElement element = d as FrameworkElement; 
      if (element == null) 
       return; 

      ResourceDictionary oldValue = e.OldValue as ResourceDictionary; 
      if (oldValue != null) 
      { 
       foreach (DictionaryEntry entry in oldValue) 
       { 
        if (element.Resources.Contains(entry.Key) && element.Resources[entry.Key] == entry.Value) 
         element.Resources.Remove(entry.Key); 
       } 
      } 

      ResourceDictionary newValue = e.NewValue as ResourceDictionary; 
      if (newValue != null) 
      { 
       foreach(DictionaryEntry entry in newValue) 
       { 
        element.Resources.Add(entry.Key, entry.Value); 
       } 
      } 
     } 
    } 
} 

而且它的用法很相似,你已经尝试过:

<Style TargetType="StackPanel"> 
    <Setter Property="assets:Utils.AdditionalResources"> 
     <Setter.Value> 
      <ResourceDictionary> 
       <Style TargetType="Button"> 
        <Setter Property="Margin" Value="20" /> 
       </Style> 
      </ResourceDictionary> 
     </Setter.Value> 
    </Setter> 
</Style>