如何在Windows Phone7中的ListBox中查找ListItem的对象

时间:2011-12-21 11:22:34

标签: windows-phone-7

我有一个ListBox,这里我绑定了IList Like(Cities)。

我想在Windows Phone7中使用.NET中的OnItemDataBound等事件。

就像每个城市都被绑定一样(如果10个城市这个事件会发射10次),这个事件将会发生,所以我必须对这个事件做更多的计算。在这种情况下,我必须找到绑定到ListItem的对象,以便我可以进行一些计算。在WP7中是否有类似于.NET的OnItemDataBound事件。

<ListBox Loaded="lstFlights_Loaded" Height="635" x:Name="lstFlights"   
                         ScrollViewer.VerticalScrollBarVisibility="Auto" Grid.Row="1">
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                            <Border CornerRadius="10" Margin="10">
                                <Border.Background>
                                    <ImageBrush ImageSource="../Images/rowbg.png"></ImageBrush>
                                </Border.Background>
//Some data here
     </Border>

                        </DataTemplate>
                    </ListBox.ItemTemplate>
                </ListBox>

我正在绑定以下数据:

lstFlights.ItemsSource = objCities;

on绑定每个城市我想要一个事件来填充一些列表项(例如:我想要更改文本块文本等),根据绑定到ListItem的City。要做到这一点,我需要像WP7中的OnItemDataBound这样的事件。我有下面的列表选择器:

                                                                                                                      

在SelectionChanged事件上,我也想更改列表项。

还有一件事IList(objCities)来自服务,因此我无法更改该对象 因此,如果我想更改列表框中的任何TextBlock,我已经做了FindName,我必须为每个绑定的城市分配计算值。

2 个答案:

答案 0 :(得分:1)

CollectionChanged集合中有ObservableCollection个事件,用于添加/删除新元素。

ListBox提供了一些访问ListBoxItem的方法。您可以在list.ItemContainerGenerator课程中看到它们。

您可以一起使用它来获得所需的结果。

有一个简短的例子,展示如何在某些条件下(无论是否)为新添加的项目制作红色前景:

ObservableCollection<string> items = new ObservableCollection<string>();

    public MainPage()
    {
        InitializeComponent();

        items.CollectionChanged += (s, e) =>
        {
            Dispatcher.BeginInvoke(() =>
            {
                if (e.NewItems != null)
                {
                    foreach (var item in e.NewItems)
                    {
                        ListBoxItem listitem = (ListBoxItem)list.ItemContainerGenerator.ContainerFromItem(item);
                        if (DateTime.Parse(listitem.Content.ToString()).Second % 2 == 0)
                        {
                            listitem.Foreground = new SolidColorBrush(Color.FromArgb(255, 255, 0, 0));
                        }
                    }
                }
            });
        };
        list.ItemsSource = items;            
    }

    private void AddButton_Click(object sender, System.Windows.RoutedEventArgs e)
    {
        items.Add(DateTime.Now.ToLongTimeString());
    }

    private void RemoveButton_Click(object sender, System.Windows.RoutedEventArgs e)
    {
        Random rnd = new Random();
        if (items.Count > 0)
        {
            int index = rnd.Next(0, items.Count);
            items.RemoveAt(index);
        }
    }
}

答案 1 :(得分:1)

如何使用ItemsChanged ListBox的{​​{1}}事件呢?

ItemContainerGenerator