如何在UI中更新ObservableCollection?

时间:2011-09-03 18:54:54

标签: c# silverlight windows-phone-7 observablecollection

foreach (var t in ((App)App.Current).CollectionMessages)
  if (t.Uid.ToString() == uid)
    t.TexT = z;

收集消息中的项目,TexT失败将文本更改为我想要的内容。但是UI没有变化,它显示了旧的价值。怎么了?请帮帮我。

Xaml:

   <Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <StackPanel Margin="0,0,0,0">
        <TextBlock Text="Диалоги" Style="{StaticResource PhoneTextNormalStyle}" FontSize="{StaticResource PhoneFontSizeLarge}"/>
    </StackPanel>
<Grid Grid.Row="2">
                <Grid d:LayoutOverrides="GridBox" >
                    <ListBox  x:Name="mess_list"  ItemsSource="{Binding}" >
                        <ListBox.ItemTemplate>
                            <DataTemplate >
                                <Grid>
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition Width="Auto"/>
                                        <ColumnDefinition Width="*"/>
                                    </Grid.ColumnDefinitions>

                                        <TextBlock Text="{Binding TexT}" " />

...

2 个答案:

答案 0 :(得分:3)

您需要确保t类型的类实现INotifyPropertyChangedMSDN),并在设置{{1}时触发PropertyChanged事件}}

答案 1 :(得分:3)

您需要实现INotifyPropertyChanged接口并引发属性更改事件,以便UI知道它必须更新。

这个How to:页面有一个有效的例子。你基本上需要这个代码:

public event PropertyChangedEventHandler PropertyChanged;

private void NotifyPropertyChanged(String info)
{
    if (PropertyChanged != null)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(info));
    }
}

当您要更新的内容发生更改时会调用它。因此TexT的代码变为:

private string localTexT
public string TexT
{
    get { return localTexT; }
    set
    {
        localTexT = value;
        NotifyPropertyChanged("TexT");
    }
}

从您的更新中看起来您已经ItemsSourceTextBlock的绑定正确无误。但是,您是否设置了视图的DataContext