使用CollectionEvent和NotifyPropertyChange通过单独的线程刷新XAML / UI中的列表框绑定

时间:2016-10-27 18:28:04

标签: c# wpf multithreading xaml

我在C#.NET 4.x中编写了一个启动UI的程序,在UI中有一个ListBox,程序应该每隔x个时间刷新一次构建的ListBox(这个部分还没有构建),参见XAML如下:

<Grid.Resources>
      <src:PresortersInfos x:Key="presortersInfos"/>
</Grid.Resources>

<ListBox Name="lblNow" ItemsSource="{StaticResource presortersInfos}" Width="118" Margin="61,257,0,65" Grid.ColumnSpan="3" HorizontalAlignment="Left" Grid.RowSpan="2" Grid.Column="8">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <TextBlock Padding="5,0,5,0" Text="{Binding Name, Mode=OneWay, NotifyOnTargetUpdated=True}" TargetUpdated="OnTargetUpdated"/>
                <TextBlock Text="{Binding NumofItemsPresent, Mode=OneWay, NotifyOnTargetUpdated=True}" TargetUpdated="OnTargetUpdated"/>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

以下是更新上面列表框的代码,但仅在启动时(应用程序的初始启动):

public class PresortersInfo
{
    public String Name { get; set; }
    public String NumofItemsPresent { get; set; }

    public PresortersInfo(String name, String numofItemsPresent)
    {
        this.Name = name;
        this.NumofItemsPresent = numofItemsPresent;
    }
}

public class PresortersInfos : ObservableCollection<PresortersInfo>
{
    List<TrackingType> DataList = new List<TrackingType>();

    SharedMemoryFile memoryfile = new SharedMemoryFile(@"\\serveName\c$\data\files\fileName.dat");
    string errorString = null;

    public PresortersInfos()
    {
        int numofLoops = Convert.ToInt16(ConfigurationManager.AppSettings["numberofSystems"]);
        string[] system_names = new string[numofLoops];
        system_names = ConfigurationManager.AppSettings["arrayVar"].Split(',');

        memoryfile.ReadAllitems(out DataList, out errorString);
        int counterofitemsinSystem= 0;
        int i = 0;

        while (i < numofLoops)
        {
            counterofitemsinSystem= DataList.Where(f => f.LastRID.ToString().Contains(system_names[i]) & f.Flag == true).Count();
            Add(new PresortersInfo("SystemName" + system_names[i], counterofitemsinSystem.ToString()));
            i++;
        }  
    }
}

首次初始化应用程序时,最初向其添加信息后,需要能够刷新ListBox(更具体地说是“Name”和“NumofItemsPresent”)。此任务应该在与程序其余部分不同的线程上完成,这样的线程应该在x时间运行。如果你能提供剩下的代码来完成我们的任务,我将非常感激。

0 个答案:

没有答案