I'm currently working on a MAUI Project and i'm trying to create a dynamicObject and bind it to a label ( final goal is not a label but it's easier to test on a label) But nothing is displayed I tried with .net7 and .net 8
My dynamic object look like this :
public class DynamicObjectTest : DynamicObject, INotifyPropertyChanged
{
public Dictionary<string, object> _dictionary = new Dictionary<string, object>();
public event PropertyChangedEventHandler PropertyChanged = delegate { };
public void SetPropertyValue(string propertyName, object value)
{
if (_dictionary.ContainsKey(propertyName)) {
_dictionary[propertyName] = value;
}
else {
_dictionary.Add(propertyName, value);
}
OnPropertyChanged(propertyName);
}
public override IEnumerable<string> GetDynamicMemberNames()
{
return _dictionary.Keys.ToArray();
}
public object GetPropertyValue(string propertyName)
{
return _dictionary.ContainsKey(propertyName) ? _dictionary[propertyName] : null;
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
bool ret = base.TryGetMember(binder, out result);
if (ret == false)
{
result = GetPropertyValue(binder.Name.ToLower());
if (result != null)
{
ret = true;
}
}
return ret;
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
bool ret = base.TrySetMember(binder, value);
if (ret == false)
{
SetPropertyValue(binder.Name.ToLower(), value);
ret = true;
}
return ret;
}
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
And my label looks like that
dynamic dynamicObject = new DynamicObjectTest();
dynamicObject.name = "test dynamic";
Label dynamicLabel = new Label();
dynamicLabel.BindingContext = dynamicObject;
dynamicLabel.SetBinding(Label.TextProperty, "name");
MainStack.Add(dynamicLabel);
I tried the same code with a regular class and it's working
I have this XAML link error :
'name' property not found on 'TestNet8.DynamicGridPage+DynamicObjectTest', target property: 'Microsoft.Maui.Controls.Label.Text'
The TryGetMember function is never trigged Do you have an idea ?