在XAML中定义一个集合



我想创建一个绑定到XAML内部定义的字符串集合。

在WPF中,我可以创建一个ArrayList作为一个带密钥的资源,准备用作绑定的源(使用StaticResource)。

这在Xamarin Forms中是可能的吗?

编辑:我已经尝试过这个XAML与@Stephane Delcroix提出的解决方案,但我得到一个未处理的异常:

<?xml version="1.0" encoding="utf-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:sys="clr-namespace:System;assembly=mscorlib"
             x:Class="ReferenceApp.Views.GamesPage"
             Title="Games">

    <ContentPage.Resources>
        <x:Array Type="{x:Type sys:String}" x:Key="array">
            <x:String>Hello</x:String>
            <x:String>World</x:String>
        </x:Array>
    </ContentPage.Resources>
    <Grid />
</ContentPage>

但是,如果我删除<x:Array >... </x:Array>

,则不会抛出异常。

我做错了什么?

我看到您正在使用XF标准标记扩展。你的错误似乎是在Type="{x:Type sys:String}",而不是sys:String你应该写x:String它出现在常见的xmlns:x

在这个示例中,我用字符串

填充一个listview
<ListView Margin="10">
    <ListView.ItemsSource>
        <x:Array Type="{x:Type x:String}">
            <x:String>Hello</x:String>
            <x:String>World</x:String>
        </x:Array>
    </ListView.ItemsSource>            
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <Label Text="{Binding}" />
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>                
</ListView>

您可以使用内置的x:Array

<x:Array Type="{x:Type sys:String}" x:Key="array">
    <x:String>Hello</x:String>
    <x:String>World</x:String>
</x:Array>

sys定义为xmlns:sys="clr-namespace:System;assembly=mscorlib"

或任何您喜欢的集合,例如List

<scg:List x:TypeArguments="{x:Type sys:String}" x:Key="genericList">
    <x:String>Hello</x:String>
    <x:String>World</x:String>
</scg:List>

与前面定义的sys相同,scgxmlns:scg="clr-namespace:System.Collections.Generic;assembly=mscorlib"

这是对更新后的问题的回答。

<x:string>只支持常量值。您可以使用标记扩展

来解决此问题。

它的功能很简单:返回参数。

using System;
using Xamarin.Forms.Xaml;
namespace YOURAPP.Extensions
{
    public class StringExtension : IMarkupExtension
    {
        public string Value { get; set; }
        public object ProvideValue(IServiceProvider serviceProvider)
        {
            return Value;
        }
    }
}

在视图中这样使用:

  1. xmlns:ext="clr-namespace:YOURAPP.Extensions"添加到根元素
  2. <x:string> <ext:StringExtension Value="{anything here}" />

注意,这会导致Add被调用到IEnumerable。对于自定义控件,您需要初始化(以避免NullReferenceException)和ObservableCollection,以确保视图在添加

时更新。

最新更新