Silverlight中的嵌套样式(如CSS)而不是WPF的吊坠



我的任务是在每个嵌套在每个stackpanel中的按钮上设置一个20px的边距。

在wpf中,我在应用程序中使用此代码。归纳:

<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手动上的键设置样式?

在Silverlight中,无法简单地做什么,可以使用附件的依赖属性完成。这是这样的属性,可以做您想要的 - 将条目添加到Elements ResourceCtionalies中。

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>

最新更新