C#ListBox更新绑定文本

时间:2014-11-07 17:28:59

标签: c# xaml binding listbox windows-phone-8.1

我在WP8.1上有一个ListBox,想在那里绑定一些项目。这样做很好,但更改ItemSource上的值并不会改变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>

我通过

绑定项目
ObservableCollection<LBItemStruct> AllMyItems = new ObservableCollection<LBItemStruct>();

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

当我现在想要更改TextBlock文本时,没有任何反应

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

当我点击面板(通过调试检查)时,PanelTap_Tapped被触发,但TextBlock文本没有改变

1 个答案:

答案 0 :(得分:2)

如果您希望在属性更改时更新视图,则需要使源对象实现INotifyPropertyChaned,并引发PropertyChanged事件:

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