Выбор кнопки закрытия другой вкладки закрывает текущую вкладку - PullRequest
0 голосов
/ 21 ноября 2019

Я создаю приложение, в котором новые вкладки создаются динамически. Я добавил кнопку закрытия для каждой вкладки, чтобы закрыть ее.

Проблема:

Если у меня открыто несколько вкладок, и я в данный момент на вкладке 2, и я выбираю кнопку закрытия tab4, затем tab2 закрывается. Я также использовал привязку данных моего TabControl с помощью RelayCommand. Но это также имело ту же проблему. Пожалуйста, предложите, где я ошибся и что я могу добавить в свой код.

Ниже приведен мой код.

XAML:

<TabControl x:Name="tabControl1" HorizontalAlignment="Stretch" MinHeight="50" Margin="0,0,0,0.2" Width="1215" ItemsSource="{Binding Titles, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Height="454" VerticalAlignment="Bottom">
  <TabControl.ItemTemplate>
    <DataTemplate>
      <StackPanel Orientation="Horizontal" Height="21">
        <TextBlock Text="{Binding Header}" />
        <Button Name="BtnClose" Content="X" Cursor="Hand" DockPanel.Dock="Right" Focusable="False" FontFamily="Courier" FontSize="9" FontWeight="Bold" Margin="0,1,0,0" Padding="0" HorizontalAlignment="Right" VerticalContentAlignment="Bottom" Width="16" Height="16"
          Command="{Binding DataContext.CloseTabCommand,RelativeSource={RelativeSource AncestorType={x:Type Window}}}" CommandParameter="{Binding ElementName=tabControl1,Path=SelectedItem}" />
        <!--Click="BtnClose_Click"-->
      </StackPanel>
    </DataTemplate>
  </TabControl.ItemTemplate>
  <TabControl.ContentTemplate>
    <DataTemplate>
      <RichTextBox Margin="10" VerticalScrollBarVisibility="Visible">
        <FlowDocument>
          <Paragraph FontSize="12" FontFamily="Courier New">
            <Run Text="{Binding Content}"></Run>
          </Paragraph>
        </FlowDocument>
      </RichTextBox>
    </DataTemplate>
  </TabControl.ContentTemplate>
</TabControl>

Мой класс ViewModel, в котором я создаюКласс Tab Item "Item" , который будет содержать вкладку Content и заголовок.

 public class MainWindowViewModel: INotifyPropertyChanged {
  public MainWindowViewModel() {
   Titles = new ObservableCollection < Item > ();
  }

  public class Item: INotifyPropertyChanged {
   public string Header {
    get;
    set;
   }
   //public string Content { get; set; }
   private string _content;

   public static int _count = -1;
   public int Count {
    get {
     return _count;
    }
    set {
     _count = value; /* OnPropertyChanged(nameof(Count));*/
    }
   }

   public string Content {
    get {
     return _content;
    }
    set {
     _content = value;
     OnPropertyChanged(nameof(Content));
    }
   }
   public Item() {
    _count++; //increase the count of tab. This will represent the index of the tab
   }

   public event PropertyChangedEventHandler PropertyChanged;
   private void OnPropertyChanged(string propertyName) {
    var handler = PropertyChanged;
    handler ? .Invoke(this, new PropertyChangedEventArgs(propertyName));
   }
  }
  public ObservableCollection < Item > Titles {
   get {
    return _titles;
   }
   set {
    _titles = value;
    OnPropertyChanged("Titles");
   }
  }

  static int tabs = 1;
  private ObservableCollection < Item > _titles;

  private RelayCommand < Item > _closeTabCommand;
  public RelayCommand < Item > CloseTabCommand {
   get {
    return _closeTabCommand ?? (_closeTabCommand = new RelayCommand < Item > (
      (t) => {
       Titles.Remove(t);
      }));
   }
  }

  public event PropertyChangedEventHandler PropertyChanged;
  private void OnPropertyChanged(string propertyName) {
   var handler = PropertyChanged;
   handler ? .Invoke(this, new PropertyChangedEventArgs(propertyName));
  }
 }

MainWindow.xaml.cs

private void BtnClose_Click(object sender, RoutedEventArgs e) {
  //remove tab
  MainWindowVMObj.RemoveTabItem(tabControl1.SelectedIndex);
 }
...