I am fairly new to WPF, C#, and the MVVM structure so excuse my ignorance. I am simply trying to create a new tab when a file is opened. My logic is all in the viewmodel including opening files which is called through binding in the xaml file so I am confused how I am supposed to get the view to create new tab once a file is opened without communication between the two. Maybe there is something I am missing, maybe my approach is completely incorrect, I’m not sure.
I have recently found a way to bind 2 commands to 1 event but if it creates a tab every time someone clicks ‘open’ it will be problematic especially if the user cancels. I have looked into having the view and viewmodel communicate as there is ways to do so but I am trying everything possible to avoid that and completely breaking the rules of MVVM.
>Solution :
There are many ways:
-
TabControl supports ItemsSource and you can simply add a new element to the ObservableCollection from the ViewModel, which will be updated immediately. Example: How do I bind a TabControl to a collection of ViewModels?
-
If the property from the ViewModel supports INotifyPropertyChanged, then you can update it.
[Reactive] // ReactiveUI.Fody
public string IsTabVisible { get; private set; }
<TabItem Visibility={Binding IsTabVisible, Converter={StaticResource BoolToVisibilityConverter} />
</TabItem>
- A complicated but good way, using Prism(and partially ReactiveUI) you can make navigation to your tab.
If you are a beginner, then I advise you to use the first method.