DynamicResource不适用于Xamarin中的自定义类型属性



我们已经尝试为我的自定义类属性绑定动态资源。但是DynamicResource对对象类型属性工作良好,但对双重类型属性不起作用。请参阅下面的代码。

您可以通过设置PropertyA属性更改方法的断点来确认未为PropertyA设置的动态资源。

对于PropertyB属性更改方法,断点命中动态资源值。

<ContentPage.Resources>
<ResourceDictionary>
<x:Double x:Key="MediumFont">25</x:Double>
</ResourceDictionary>
</ContentPage.Resources>
<StackLayout>

<local:TestClass >
<local:TestClass.HintStyle>
<local:LabelStyle PropertyA="{DynamicResource MediumFont}" PropertyB="{DynamicResource MediumFont}"/>
</local:TestClass.HintStyle>
</local:TestClass>


</StackLayout>
public class TestClass :View
{
public LabelStyle HintStyle
{
get => (LabelStyle)GetValue(HintStyleProperty);
set => SetValue(HintStyleProperty, value);
}
public static readonly BindableProperty HintStyleProperty =
BindableProperty.Create(nameof(HintStyle), typeof(LabelStyle), typeof(TestClass),
new LabelStyle(), BindingMode.Default);
}
public class LabelStyle :View
{
public double PropertyA
{
get => (double)GetValue(PropertyAProperty);
set => SetValue(PropertyAProperty, value);
}
public static readonly BindableProperty PropertyAProperty =
BindableProperty.Create(nameof(PropertyA), typeof(double), typeof(LabelStyle), 
0d, BindingMode.Default, null, OnPropertyAChanged);
private static void OnPropertyAChanged(BindableObject bindable, object oldValue, object newValue)
{
}
public object PropertyB
{
get => GetValue(PropertyBProperty);
set => SetValue(PropertyBProperty, value);
}
private static readonly BindableProperty PropertyBProperty =
BindableProperty.Create(nameof(PropertyB), typeof(object), typeof(LabelStyle),
null, BindingMode.Default, null, OnPropertyBChanged);
private static void OnPropertyBChanged(BindableObject bindable, object oldValue, object newValue)
{
}
}

请帮帮我。为什么动态资源不适用于PropertyA。

解决方案1:

使用StaticResource而不是DynamicResource。动态资源存储Key;MediumFont";,它是一个字符串,因此不会绑定到double类型的属性。

<local:TestClass>
<local:TestClass.HintStyle>
<local:LabelStyle PropertyA="{StaticResource MediumFont}" PropertyB="{StaticResource MediumFont}"/>
</local:TestClass.HintStyle>
</local:TestClass>

解决方案2:

当使用DynamicResource时,我们必须为可绑定的属性类型使用类型对象。然后将PropertyAProperty设置为私有。

public object PropertyA
{
get => GetValue(PropertyAProperty);
set => SetValue(PropertyAProperty, value);
}
private static readonly BindableProperty PropertyAProperty =
BindableProperty.Create(nameof(PropertyA), typeof(object), typeof(LabelStyle),
null, BindingMode.Default, null, OnPropertyAChanged);
private static void OnPropertyAChanged(BindableObject bindable, object oldValue, object newValue)
{
}

最新更新