user3079834
user3079834

Reputation: 2234

C# ListBox Update Binding Text

I have a ListBox on WP8.1 and want to Bind some items in there. That works all fine, but changing a value on the ItemSource doesn't change anything in the ListBox

<ListBox x:Name="myListBox" Width="Auto" HorizontalAlignment="Stretch" Background="{x:Null}" Foreground="{x:Null}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel x:Name="PanelTap" Tapped="PanelTap_Tapped">
                <Border x:Name="BorderCollapsed">
                    <StackPanel Margin="105,0,0,0">
                        <TextBlock Text="{Binding myItem.location, Mode=TwoWay}" />
                    </StackPanel>
                </Border>
    </ListBox.ItemTemplate>
</ListBox>

I bind the items via

ObservableCollection<LBItemStruct> AllMyItems = new ObservableCollection<LBItemStruct>();

with

public sealed class LBItemStruct
{
    public bool ext { get; set; }
    public Container myItem { get; set; }
}
public sealed class Container
{
    public string location{ get; set; }
    ...
}

and when I now want to change the TextBlock Text, nothing happens

private void PanelTap_Tapped(object sender, TappedRoutedEventArgs e)
{
    int sel = myListBox.SelectedIndex;
    if (sel >= 0)
    {
        myListBox[sel].myItem.location = "sonst wo";
    }
}

The PanelTap_Tapped gets triggered, when I tap the Panel (checked via Debug), but the TextBlock Text does not change

Upvotes: 1

Views: 261

Answers (1)

McGarnagle
McGarnagle

Reputation: 102793

If you want the view to update when a property changes, then you need to have the source object implement INotifyPropertyChaned, and raise the PropertyChanged event:

public sealed class Container : INotifyPropertyChanged
{
    public string location
    { 
        get { return _location; }
        set { _location = value; RaisePropertyChanged("location"); }
    }
    private string _location;
    ... 

    public event PropertyChangedEventHandler PropertyChanged;

    private void RaisePropertyChanged(string propName)
    {
        var handler = PropertyChanged;
        if (handler != null)
            handler(new PropertyChangedEventArgs(this, propName));
    }
}

Upvotes: 2

Related Questions