C# Silverlight中嵌套样式(如CSS)的挂件,而不是WPF
我的任务是在每个StackPanel中嵌套的每个按钮上设置20px的边距 在WPF中,我在应用程序中使用这段代码。参考资料:C# Silverlight中嵌套样式(如CSS)的挂件,而不是WPF,c#,css,silverlight,C#,Css,Silverlight,我的任务是在每个StackPanel中嵌套的每个按钮上设置20px的边距 在WPF中,我在应用程序中使用这段代码。参考资料: <Style TargetType="StackPanel"> <Style.Resources> <Style TargetType="Button"> <Setter Property="Margin" Value="20" /> </Style> </Style
<Style TargetType="StackPanel">
<Style.Resources>
<Style TargetType="Button">
<Setter Property="Margin" Value="20" />
</Style>
</Style.Resources>
</Style>
Silverlight中缺少“Style.Resources”-标记。但我尝试了以下代码:
<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中,无法简单完成的事情可以使用附加的依赖属性完成。 这就是这样一个属性,它可以做您想要做的事情—将条目添加到元素资源字典中
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>