开发者

How to update ObservableCollection in UI?

开发者 https://www.devze.com 2023-04-02 00:53 出处:网络
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, i
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 Pho开发者_如何学PythonneTextNormalStyle}" 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}" " />

...


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.


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?

0

精彩评论

暂无评论...
验证码 换一张
取 消