Xamarin.Forms x:共享 [英] Xamarin.Forms x:Shared
问题描述
我当前正在使用的Xamarin.Forms应用程序有问题.我创建的资源正在多个控件中使用,这些控件使用同一对象将其呈现到屏幕上.我以为使用x:Shared="False"
属性(按照 https://docs.microsoft.com/zh-cn/dotnet/framework/xaml-services/x-shared-attribute )即可解决.它不是:(有什么想法可以在.xaml中创建同一对象而不必定义多个资源吗?
I have an issue with a Xamarin.Forms application I am currently working on. The resource I have created is being used within multiple controls, the controls are using the same object to render out onto the screen. I thought using the x:Shared="False"
attribute (as per https://docs.microsoft.com/en-us/dotnet/framework/xaml-services/x-shared-attribute) would get around this. It does not :( Any ideas how to create the same object in .xaml without having to define multiple resources?
<Grid.Resources>
<ResourceDictionary>
<SharedShapes:Circle x:Shared="False" x:Key="SpecCircle" Color="{StaticResource AccentColor}"/>
</ResourceDictionary>
</Grid.Resources>
<SharedControls:ImageButton Grid.Row="0" Grid.Column="0" Shape="{StaticResource SpecCircle}"...
<SharedControls:ImageButton Grid.Row="1" Grid.Column="0" Shape="{StaticResource SpecCircle}"...
.
.
.
非常感谢!
推荐答案
您提到的链接主要讨论WPF框架-Xamarin格式不支持x:Shared
.
The link you mentioned talks primarily about WPF framework - I don't think x:Shared
is supported in Xamarin forms.
为避免多次声明形状-您可以使用DataTemplate
,并将其注册为StaticResource
.
To avoid having to declare shape multiple times - you can make use of DataTemplate
, and register that as a StaticResource
.
然后,修改/扩展ImageButton
以添加类型为DataTemplate
的可绑定属性,该属性在设置时使用
And, modify/extend ImageButton
to add a bindable property of type DataTemplate
, which when set inflates the template into Shape
object using CreateContent()
method.
public DataTemplate ShapeTemplate
{
get { return (DataTemplate)GetValue(ShapeTemplateProperty); }
set { SetValue(ShapeTemplateProperty, value); }
}
public static readonly BindableProperty ShapeTemplateProperty = BindableProperty.Create(
nameof(ShapeTemplate),
typeof(DataTemplate),
typeof(ImageButton),
propertyChanged: (bObj, oldValue, newValue) =>
{
var view = bObj as ImageButton;
if (view != null && newValue != null)
view.Shape = (View)newValue.CreateContent();
}
);
样品用量
<Grid.Resources>
<ResourceDictionary>
<DataTemplate x:Key="SpecCircleTemplate">
<SharedShapes:Circle Color="{StaticResource AccentColor}"/>
</DataTemplate>
</ResourceDictionary>
</Grid.Resources>
<SharedControls:ImageButton Grid.Row="0" Grid.Column="0"
ShapeTemplate="{StaticResource SpecCircleTemplate}"...
<SharedControls:ImageButton Grid.Row="1" Grid.Column="0"
ShapeTemplate="{StaticResource SpecCircleTemplate}"...
这篇关于Xamarin.Forms x:共享的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!