-
Notifications
You must be signed in to change notification settings - Fork 1
/
CssStyleExtension.cs
55 lines (45 loc) · 1.63 KB
/
CssStyleExtension.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
using System;
using System.Linq;
using System.Windows;
using System.Windows.Markup;
namespace WpfCssStyle
{
[MarkupExtensionReturnType(typeof(Style))]
public class CssStyleExtension : MarkupExtension
{
/// <summary>
/// Set space-separated style names i.e. "size16 gray verdana".
/// </summary>
public string Names { private get; set; }
public override object ProvideValue(IServiceProvider serviceProvider)
{
return Names.Split(new[] { ' ' })
.Select(x => Application.Current.TryFindResource(x)
as Style)
.Aggregate(new Style(), RecursivelyMergeStyles);
}
private static Style RecursivelyMergeStyles(Style accumulator, Style next)
{
if (accumulator == null || next == null)
return accumulator;
if (next.BasedOn != null)
RecursivelyMergeStyles(accumulator, next.BasedOn);
MergeStyle(accumulator, next);
return accumulator;
}
private static void MergeStyle(Style targetStyle, Style sourceStyle)
{
if (targetStyle == null || sourceStyle == null)
{
return;
}
targetStyle.TargetType = sourceStyle.TargetType;
// Merge the Setters...
foreach (var setter in sourceStyle.Setters)
targetStyle.Setters.Add(setter);
// Merge the Triggers...
foreach (var trigger in sourceStyle.Triggers)
targetStyle.Triggers.Add(trigger);
}
}
}