【问题标题】:XAML ItemsControl to repeat X number of times?XAML ItemsControl 重复 X 次?
【发布时间】:2015-07-05 20:01:03
【问题描述】:

我正在使用 Windows Phone 8.1 应用程序(非 SL),我的 ViewModel 上有一个名为 Apples 的属性,其值为 3

我想要一个中继器来绘制x Apples(我有图像),其中x 是我的ViewModel 上Apples 的值。

如何在 XAML 中实现这一点?我目前有以下内容:

<ItemsControl Grid.Column="0" ItemsSource="{Binding Lives, Converter={}}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <!-- image here -->
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

我猜我需要以某种方式将整数转换为某种项目?

【问题讨论】:

  • 推荐的命名约定是使用属性名称AppleCount 表示数字,使用Apples 表示集合类型

标签: xaml windows-phone-8.1


【解决方案1】:
ItemsSource="{Binding SomeNumber, Converter={StaticResource NumberToItemsConverter}}"

public class NumberToItemsConverter: IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var number = (int)value;
        return Enumerable.Range(1, number);
    }
 }

【讨论】:

    【解决方案2】:

    你有两个选择:

    选项一

    您需要创建一个苹果列表,并将 ItemsControl 绑定到它。 这是一个例子:

    int x = 3;
    Apples = new ObservableCollection<Apple>(); 
    /*your ViewModel must implement INotifyPropertyChanged so the UI will be
    notified by the changes in the Apples list*/
    
    for(int i = 0; i < x; i++)
    {
       Apples.Add(new Apple());
    }
    //now your ItemsControl has 3 apples
    

    选项二 您在后面的代码中创建了一个执行我上面编写的自定义控件。在该控件中,您创建一个 int 类型的依赖项属性,当该属性发生更改时,您可以将项目添加到您的 ItemsControl。

    【讨论】:

      【解决方案3】:

      如果您尝试使用包含 5 个项目的 GridView(每个项目的样式为苹果)会怎样。 GridView 的源代码由ObservableCollection 提供支持。当一个生命被“消耗”时,只需从集合中移除一个项目。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-04-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-30
        • 2020-02-18
        相关资源
        最近更新 更多