简体   繁体   中英

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

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));
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM