UWP使用不断更新的数组更新itemscontrol

时间:2017-01-26 23:14:12

标签: c# xaml uwp

我有一个不断更改其值的数组,因此我希望每次数组的值都能刷新应用程序UI。我有这个与itemsControl绑定。我可以显示第一个数组的值,但后来我无法更新它们我尝试过.items.Clear()但它不起作用。这是.xaml和xaml.cs的片段。我实际上从这个网站的问题中获取了.xaml的代码。

的.xaml

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
        <TextBox Text="Testing" IsReadOnly="True"></TextBox>
        <ItemsControl x:Name="itemsControl"
          ItemsSource="{Binding itemsControl}"
          FontSize="24">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Grid Width="Auto"
                        Margin="0 12"
                        HorizontalAlignment="Center">
                        <Grid.RowDefinitions>
                            <RowDefinition Height="Auto" />

                        </Grid.RowDefinitions>

                        <StackPanel Grid.Column="0"
                                    Grid.Row="0"
                                    Orientation="Horizontal">
                            <TextBlock Name="txtblk0" Text="{Binding}" />
                        </StackPanel>

                    </Grid>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>

.xaml.cs

String c = (new String(cArray));
string[] arr = null;
string[] data = null;
if (c != null)
{
    arr = c.Split('\n');
    if (arr.Length > 0)
    {
        data = arr[0].Split(',');
    }
}

for(int index = 0; index < 4; index++)
{
    itemsControl.Items.Add(float.Parse(data[index]));
}

itemsControl.Clear();

如果有人知道如何做到这一点,我将非常感激,提前谢谢,我会尽快回答任何问题!

1 个答案:

答案 0 :(得分:0)

您缺少的是了解如何触发更新绑定。

INotifyPropertyChanged接口包含一个方法(PropertyChanged),当调用并传递时,属性的名称将告诉绑定系统该属性已更改并且绑定应该更新。
INotifyCollectionChanged与集合等效,并在集合发生更改时进行通信。即添加,删除或清除列表的内容。

ObservableCollection<T>包含INotifyCollectionChanged的实现,可以轻松处理更改的列表,集合等。

如果您使用ObservableCollection<float>代替数组,则可以修改列表并更新UI以轻松反映这一点。

作为入门者,请参阅以下内容,了解使用ObservableCollection是多么容易。

XAML:

<StackPanel>
    <Button Click="Button_Click">add an item</Button>
    <ItemsControl ItemsSource="{Binding Items}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding}" />
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
</StackPanel>

代码背后;

public MainPage()
{
    this.InitializeComponent();

    // Initialize the property
    this.Items = new ObservableCollection<string>();
    // Use self as datacontext (but would normally use a separate viewmodel)
    this.DataContext = this;
}

private void Button_Click(object sender, RoutedEventArgs e)
{
    // add a new item to the UI
    this.Items.Add(DateTime.Now.ToString());
}

// The "collection" that is shown in the UI
public ObservableCollection<string> Items { get; set; }