SevenDays
SevenDays

Reputation: 3768

How to update ObservableCollection in UI?

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

The item in CollectionMessages, filed TexT changes Text to what I want. But the UI has no changes, it shows old value. What's wrong?Please help me.

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}" " />

...

Upvotes: 0

Views: 1115

Answers (2)

ChrisF
ChrisF

Reputation: 137148

You need to implement the INotifyPropertyChanged interface and raise a property changed event so that the UI knows it has to update.

This How to: page has a worked example. You basically need this code:

public event PropertyChangedEventHandler PropertyChanged;

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

which gets called when the things you want to update get changed. So the code for TexT becomes:

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

From your update it looks like you've got the binding of the ItemsSource and TextBlock correct. However, have you set the DataContext of the view?

Upvotes: 3

i_am_jorf
i_am_jorf

Reputation: 54600

You need to make sure that the class of which t is a type implements INotifyPropertyChanged (MSDN), and fires the PropertyChanged event when you set TexT.

Upvotes: 3

Related Questions