Search code examples
c#wpfmvvm

How can I update the UI (view) based on a method from viewmodel while still following MVVM


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 a 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 are 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:

    1. 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?

    2. 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>
    
    1. 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.