0

我有一个由我自己的类动态填充的 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;
}

但是用户名没有改变...

4

1 回答 1

2

您不必改回Contentselected ListBoxItemMyOwnClass我假设是一个类,因此username在一个实例中更改引用类型将对同一对象的所有引用产生影响。您MyOwnClass应该在每次属性更改时实现INotifyPropertyChanged接口 ( MSDN ) 并引发事件。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));
    }  
}

如果你这样做就足够了:

private void timelinelistbox_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
{
   ((sender as ListBox).SelectedItem as MyOwnClass).username = "ChangedUsername";
}
于 2013-05-26T10:30:34.837 回答