问题描述
我们尝试为我的自定义类属性绑定动态资源。但是 DynamicResource 适用于对象类型属性,但不适用于 double 类型属性。请参阅下面的代码。
您可以通过为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),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),OnPropertyBChanged);
private static void OnPropertyBChanged(BindableObject bindable,object newValue)
{
}
}
请帮帮我。为什么动态资源不适用于 PropertyA。
解决方法
解决方案 1:
使用 StaticResource
而不是 DynamicResource
。动态资源存储键,在本例中为“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,OnPropertyAChanged);
private static void OnPropertyAChanged(BindableObject bindable,object oldValue,object newValue)
{
}