2014-01-20 79 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>