访问ListBoxItem子项

时间:2013-05-26 09:41:03

标签: c# xaml windows-phone-8

我有一个ListBox,它由我自己的类动态填充。这是我的列表框的一个示例:

<ListBox x:Name="mylistbox" SelectionChanged="timelinelistbox_SelectionChanged_1">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Grid>
                <TextBlock Text="{Binding userid}" Visibility="Collapsed" />
                <TextBlock Text="{Binding postid}" Visibility="Collapsed" />
                <Image Source="{Binding thumbnailurl}" />
                <TextBlock Text="{Binding username}" />
                <TextBlock Text="{Binding description}" />
                <Image Source="{Binding avatar}" />
            </Grid>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

当ListBox的SelectedItemChanged事件被触发时,我得到了我的ListBoxItem。 但是现在我想改变那个ListBoxItem中的子节点...但我似乎无法访问ListBoxItem的子节点?

我试过了:

private void timelinelistbox_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
{
    //Get the data object that represents the current selected item
    MyOwnClass data = (sender as ListBox).SelectedItem as MyOwnClass;

    //Get the selected ListBoxItem container instance    
    ListBoxItem selectedItem = this.timelinelistbox.ItemContainerGenerator.ContainerFromItem(data) as ListBoxItem;

    // change username and display
    data.username = "ChangedUsername";
    selectedItem.Content = data;
}

但用户名不会改变......

1 个答案:

答案 0 :(得分:2)

您无需更改所选Content的{​​{1}}。我假设ListBoxItem是一个类,因此引用类型,因此在一个实例中更改MyOwnClass将对所有对同一对象的引用生效。每次属性更改时,username都应实施MyOwnClass界面(MSDN)并举起INotifyPropertyChanged个事件。就像你通知所有绑定控件一样,属性已经改变并需要刷新:

PropertyChanged

如果你这样做就足够了:

public class MyOwnClass : INotifyPropertyChanged
{
    private string _username;

    public string username 
    {
        get { return _username ; }
        set
        {
            if (_userName == value) return;
            _userName = value;
            NotifyPropertyChanged("username");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    public void NotifyPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }  
}