繁体   English   中英

C#UWP如何在xaml中显示string []?

[英]C# UWP How to display a string[] in xaml?

我有一个从API填充的公交车起点字符串[]。 我想知道是否有任何方法可以在xaml中显示此数组?

我在MVVM模式中工作,我的ViewModel看起来像这样:

    private string[] _departures = new string[7];
    public string[] Departures
    {
        get
        {
            return _departures;
        }
        set
        {
            _departures = value;
            OnPropertyChanged();
        }
    }

我的MainPage.xaml看起来像这样:

        <ItemsControl ItemsSource="{Binding Departures}">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Departures}"/>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>

这就是现在的样子: 结果

确保视图的DataContext包含具有Departures属性的对象:

public sealed partial class MainPage : Page
{
    public MainPage()
    {
        InitializeComponent();
        DataContext = new ViewModel();
    }
}

public class ViewModel
{
    public string[] Departures { get; } = new string[] { "Now", "Then", "Later" };
}

然后此XAML起作用:

<ItemsControl ItemsSource="{Binding Departures}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding}"/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

我将创建一个扩展方法,以从string []对象获取组合字符串,并绑定将调用此方法的属性。

public static class ExtensionMethods
{
    public static string GetString(this string[] myStrings)
    {
        return string.Join(", ", myStrings); // Or however you prefer to combine the strings
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM