Gravatar.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. using System.Windows;
  2. using System.Windows.Controls;
  3. using System.Windows.Media;
  4. using HandyControl.Data;
  5. using HandyControl.Tools;
  6. namespace HandyControl.Controls;
  7. public class Gravatar : ContentControl
  8. {
  9. public static readonly DependencyProperty GeneratorProperty = DependencyProperty.Register(
  10. nameof(Generator), typeof(IGravatarGenerator), typeof(Gravatar), new PropertyMetadata(new GithubGravatarGenerator()));
  11. public IGravatarGenerator Generator
  12. {
  13. get => (IGravatarGenerator) GetValue(GeneratorProperty);
  14. set => SetValue(GeneratorProperty, value);
  15. }
  16. public static readonly DependencyProperty IdProperty = DependencyProperty.Register(
  17. nameof(Id), typeof(string), typeof(Gravatar), new PropertyMetadata(default(string), OnIdChanged));
  18. private static void OnIdChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  19. {
  20. var ctl = (Gravatar) d;
  21. if (ctl.Source != null) return;
  22. ctl.Content = ctl.Generator.GetGravatar((string) e.NewValue);
  23. }
  24. public string Id
  25. {
  26. get => (string) GetValue(IdProperty);
  27. set => SetValue(IdProperty, value);
  28. }
  29. public static readonly DependencyProperty SourceProperty = DependencyProperty.Register(
  30. nameof(Source), typeof(ImageSource), typeof(Gravatar), new PropertyMetadata(default(ImageSource), OnSourceChanged));
  31. private static void OnSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  32. {
  33. var ctl = (Gravatar) d;
  34. var v = (ImageSource) e.NewValue;
  35. ctl.Background = v != null
  36. ? new ImageBrush(v)
  37. {
  38. Stretch = Stretch.UniformToFill
  39. }
  40. : ResourceHelper.GetResourceInternal<Brush>(ResourceToken.SecondaryRegionBrush);
  41. }
  42. public ImageSource Source
  43. {
  44. get => (ImageSource) GetValue(SourceProperty);
  45. set => SetValue(SourceProperty, value);
  46. }
  47. }