2011-02-23 6 views

답변

1

할 수 있습니다 :에

  • 설정 NotifyOnTargetUpdated 해당 이벤트 처리기에서 ItemsSource.CollectionChanged
  • 0으로 선택된 인덱스를 설정하기위한
  • 등록하는 이벤트 처리기에서 Binding.TargetUpdated
  • 에 대한 이벤트 처리기를 추가 바인딩

문제는 바인딩에 NotifyonTargetUpdated을 설정하여 첫 번째 이벤트가 실행되지 않았거나 컬렉션이 업데이트되었지만 두 번째 이벤트가 필요하도록 동일한 컬렉션이었습니다.

ItemsControl으로 ListBox을 사용하고 MessageBox을 프록시로 사용하여 작동하는 예제입니다. 여기

는 마크 업입니다 :

<Grid> 
    <DockPanel> 
     <Button DockPanel.Dock="Top" Content="Update Target" Click="ButtonUpdateTarget_Click"/> 
     <Button DockPanel.Dock="Top" Content="Update Item" Click="ButtonUpdateItem_Click"/> 
     <ListBox Name="listBox" Binding.TargetUpdated="ListBox_TargetUpdated" ItemsSource="{Binding Items, NotifyOnTargetUpdated=True}"/> 
    </DockPanel> 
</Grid> 

여기에 코드 숨김입니다 :

public class ViewModel : INotifyPropertyChanged 
{ 
    ObservableCollection<string> items; 
    public ObservableCollection<string> Items 
    { 
     get { return items; } 
     set { items = value; OnPropertyChanged("Items"); } 
    } 

    public event PropertyChangedEventHandler PropertyChanged; 

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

void SetDataContext() 
{ 
    DataContext = viewModel; 
    viewModel.Items = new ObservableCollection<string> { "abc", "def", "ghi" }; 
} 

ViewModel viewModel = new ViewModel(); 

private void ButtonUpdateTarget_Click(object sender, RoutedEventArgs e) 
{ 
    viewModel.Items = new ObservableCollection<string> { "xyz", "pdq" }; 
} 

private void ButtonUpdateItem_Click(object sender, RoutedEventArgs e) 
{ 
    viewModel.Items[0] = "xxx"; 
} 

private void ListBox_TargetUpdated(object sender, DataTransferEventArgs e) 
{ 
    MessageBox.Show("Target Updated!"); 
    (listBox.ItemsSource as INotifyCollectionChanged).CollectionChanged += new NotifyCollectionChangedEventHandler(listBox_CollectionChanged); 
} 

void listBox_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) 
{ 
    MessageBox.Show("Item Updated!"); 
} 
0

내가 같은 문제에 직면했다. ,

  • ListBox.Items.Count

    <TextBox x:Name="txtCount" TextChanged="TextBox_TextChanged" Text="{Binding ElementName=ListBox1, Path=Items.Count, Mode=OneWay}" Visibility="Collapsed" /> 
    
    TextBox_TextChanged 이벤트에서
  • 로 축소

  • 바인드 텍스트에 텍스트 상자의

  • 공개 설정을 텍스트 상자를 만들어이 문제를 극복하기 위해, 나는 다음 단계를 사용 SelectedIndex을 0으로 설정하십시오.

    private void TextBox_TextChanged(object sender, TextChangedEventArgs e) 
    { 
        int count = 0; 
    
        if(int.TryParse(txtCount.Text,out count) && count>0) 
         ListBox1.SelectedIndex = 0; 
    
    }