2013-05-26 1 views
0

내 자신의 클래스에 의해 동적으로 채워지는 ListBox가 있습니다. 다음은 내 목록 상자의 예입니다.ListBoxItem 하위에 액세스

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

그러나 사용자 이름은

+0

당신은 또한 방법'MyOwnClass' 수준의 외모를 추가 할 수 같은'username' 속성에 관해서? – dkozl

+0

사용자 이름 변경 후 DataBind()를 호출 했습니까? – Saravanan

+0

"selectedItem.DataContext = data;"를 의미합니다. ? 그래도 작동하지 않습니다 ... –

답변

2

당신은 다시 ContentListBoxItem 선택의를 변경할 필요가 없습니다 ... 변경되지 않습니다. MyOwnClass은 클래스입니다. 따라서 참조 유형은 한 인스턴스에서 username을 변경하면 동일한 객체에 대한 모든 참조에서 효과가 있습니다. MyOwnClassINotifyPropertyChanged 인터페이스 (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"; 
} 
+0

굉장, 고마워! –