I am verifying MVVM for runtime in Unity6 while reading the official documentation.
For example, I know that I can write the following when binding to Label.text.
var label = element.Q<Label>("SampleLabel");
label.SetBinding(
new BindingId(nameof(Label.text)),
new DataBinding()
{
dataSource = viewModel,
dataSourcePath = PropertyPath.FromName(nameof(ViewModel.Label)),
dataSourceType = typeof(string),
bindingMode = BindingMode.ToTarget,
updateTrigger = BindingUpdateTrigger.OnSourceChanged,
}
);
However, since Button.clickable does not have a [CreateProperty] attribute, it does not appear to be possible to do the binding with this technique.
In writing data binding in code like this, how should I set up the binding for Button.clickable?
I understand that callbacks can be added by writing “Button clicked += ()=>{}”, but I would prefer to have function name based binding like Xamarin or WPF.
(This is because it allows us to clearly separate the design of the UI from the coding of the logic. Of course, we know that we need to prepare libraries for connections like ReactiveProperty).
I would be happy to write the following…
(or if we could bind the methods directly)
View
var button = element.Q<Button>("SampleButton");
button.SetBinding(
new BindingId(nameof(Button.clickable)),
new DataBinding()
{
dataSource = viewModel,
dataSourcePath = PropertyPath.FromName(nameof(ViewModel.OnClick)),
dataSourceType = typeof(Clickable),
bindingMode = BindingMode.ToTarget,
updateTrigger = BindingUpdateTrigger.OnSourceChanged,
}
);
ViewModel
public class ViewModel
{
private Clickable _onClick;
[CreateProperty]
public Clickable OnClick
{
get
{
return _onClick;
}
}
public ViewModel()
{
_onClick = new Clickable(OnClickCallback)
}
private void OnClickCallback()
{
UnityEngine.Debug.Log("Click!");
}
}
Does anyone have any methods or ideas for this?