2011-02-23 89 views

回答

1

您可以:

  • 上設置NotifyOnTargetUpdated結合
  • Binding.TargetUpdated
  • 添加事件處理程序在該事件處理程序註冊ItemsSource.CollectionChanged
  • 在該事件處理程序設置所選指數爲零

這個問題很可能是你沒有在綁定中設置NotifyonTargetUpdated,以便第一個事件未被觸發或集合正在更新,但它是相同的集合,所以第二個事件是必需的。

下面是一個使用ListBox作爲ItemsControlMessageBox作爲您在事件觸發時執行任何操作的代理的示例。

下面是標記:

<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; 
    
    } 
    
相關問題