12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 |
- using Avalonia;
- using Avalonia.Controls;
- using Avalonia.Data;
- using Avalonia.Data.Converters;
- using Avalonia.Markup.Xaml;
- using Avalonia.Markup.Xaml.MarkupExtensions;
- using System;
- using System.Collections.Generic;
- using System.Globalization;
- namespace ShakerApp
- {
- /// <summary>
- /// 多语言绑定时使用,没有其他任何功能
- /// </summary>
- public class ResourceBindingExtensions
- {
- public static readonly AttachedProperty<object?> BindingExtensionProperty = AvaloniaProperty.RegisterAttached<Control, object?>("BindingExtension", typeof(Control), defaultValue: null);
- public static object? GetBindingExtension(Control control) => control.GetValue(BindingExtensionProperty);
- public static void SetBindingExtension(Control control, object? value) => control.SetValue(BindingExtensionProperty, value);
- }
- public class ResourceBinding : MarkupExtension
- {
- private PathConverter converter = new PathConverter();
- public ResourceBinding(string path)
- {
- this.Path = path;
- }
- public override object ProvideValue(IServiceProvider serviceProvider)
- {
- var provideValueTargetService = (IProvideValueTarget)serviceProvider.GetService(typeof(IProvideValueTarget))!;
- var targetObject = provideValueTargetService.TargetObject as Control;
- var targetProperty = provideValueTargetService.TargetProperty as AvaloniaProperty;
- if (targetObject == null || targetProperty == null) return null;
- Binding binding = new Binding()
- {
- Path = Path,
- Converter = converter,
- ConverterParameter = new KeyValuePair<Control,AvaloniaProperty>(targetObject,targetProperty),
- Mode = BindingMode.OneWay,
- UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged,
- };
- targetObject.Bind(ResourceBindingExtensions.BindingExtensionProperty, binding);
- return null;
- }
- /// <summary>
- /// The source path (for CLR bindings).
- /// </summary>
- public string Path { get; set; }
- private class PathConverter : IValueConverter
- {
- public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
- {
- if (parameter is KeyValuePair<Control, AvaloniaProperty> p && value is string v)
- {
- p.Key.Bind(p.Value, new DynamicResourceExtension(v));
- }
- return "";
- }
- public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
- {
- throw new NotImplementedException();
- }
- }
- }
- }
|