Skip to content

Commit

Permalink
Reworked localized text binding to support any kind of bound object
Browse files Browse the repository at this point in the history
  • Loading branch information
bustedbunny committed Apr 8, 2023
1 parent 67d3902 commit 3bf2e41
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 11 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,26 @@
using System.ComponentModel;
using MVVMToolkit.Binding.Localization.Source;
using UnityEngine.Localization;
using UnityEngine.UIElements;

namespace MVVMToolkit.Binding.Localization
{
public class LocalizedTextBinding : IElementBinding
public abstract class BaseLocalizedTextBinding : IElementBinding
{
private readonly TextElement _element;
private readonly Action<VisualElement, string> _operation;
public abstract void Unbind();
}

public class LocalizedTextBinding<T> : BaseLocalizedTextBinding
{
private readonly T _boundElement;
private readonly Action<T, string> _operation;
private readonly BindingGroup _rootBinding;
private readonly LocalizedString _localizedString;

public LocalizedTextBinding(TextElement element, INotifyPropertyChanged binding, LocalizedString ls,
Action<VisualElement, string> operation)
public LocalizedTextBinding(T boundElement, INotifyPropertyChanged binding, LocalizedString ls,
Action<T, string> operation)
{
_operation = operation;
_element = element;
_boundElement = boundElement;

_localizedString = ls;

Expand All @@ -34,9 +38,9 @@ public LocalizedTextBinding(TextElement element, INotifyPropertyChanged binding,
_localizedString.GetLocalizedStringAsync().Completed += handle => { StringChanged(handle.Result); };
}

private void StringChanged(string value) => _operation(_element, value);
private void StringChanged(string value) => _operation(_boundElement, value);

public void Unbind()
public override void Unbind()
{
_rootBinding.ClearBindings();
_localizedString.Arguments?.Remove(_rootBinding);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

namespace MVVMToolkit.Binding.Localization
{
public class LocalizationTextParser : BindingParser<LocalizedTextBinding>
public class LocalizationTextParser : BindingParser<BaseLocalizedTextBinding>
{
private readonly LocalizedStringTable[] _stringTables;
private readonly Action<VisualElement, string> _bindingOperation;
Expand All @@ -26,7 +26,7 @@ public override void Process(VisualElement element, string key)
var table = GetMatchingTable(_stringTables, key);
var ls = new LocalizedString(table, key);
_lsList.Add(ls);
var binding = new LocalizedTextBinding(text, bindingContext, ls, _bindingOperation);
var binding = new LocalizedTextBinding<VisualElement>(text, bindingContext, ls, _bindingOperation);
boundingMap.Add(binding, key);
}

Expand Down

0 comments on commit 3bf2e41

Please sign in to comment.