WPF tab control and MVVM selection

前端 未结 4 1384
遥遥无期
遥遥无期 2020-12-29 04:44

I have a TabControl in an MVVM WPF application. It is defined as follows.



        
4条回答
  •  半阙折子戏
    2020-12-29 05:31

    The accepted answer is not working with DependencyObject on your ViewModel .

    I'm using MVVM with DependencyObject and Just setting the TabControl didn't work for me.The problem I had was the the property was not getting update on the View when I was setting the tab selectedIndex from the ViewModel.

    I did set the Mode to be two ways but nothing was working.

    
        ...
    
    

    The ViewModel property "SelectedTab" was getting updated all the time when I navigated between tabs. This was confirming my binding was working properly. Each time I would navigate the tabs both the Get and Set would get called in my ViewModel. But if I try to set the SelectedIndex in the ViewModel it would not update the view. ie: SelectedTab=0 or SelectedTab=1 etc... When doing the set from the ViewModel the SelectedTab 'set' method would be called, but the view would never do the 'get'.

    All I could find online was example using INotifyPropertyChanged but I do not wish to use that with my ViewModel.

    I found the solutions in this page: http://blog.lexique-du-net.com/index.php?post/2010/02/24/DependencyProperties-or-INotifyPropertyChanged

    With DependencyObject, you need to register the DependencyProperties. Not for all properties but I guess for a tabcontrol property you need to.

    Below my code:

    view.xaml

    //Not sure below if I need to mention the TwoWay mode
    
            ...
    
    

    ViewModel.cs

    public class ViewModel : DependencyObject
    {
           public static readonly DependencyProperty SelectedTabDP =  DependencyProperty.Register("SelectedTab", typeof(int), typeof(ViewModel));
    
           public int SelectedTab
           {
              get { return (int)GetValue(SelectedTabDP); }
              set { SetValue(SelectedTabDP, value); }
           }
    }
    

    Basically all I had to do was to actually register the dependency property (DependencyProperty) as you can see above.

    What made this hard to figure out was that I have a bunch of other Properties on that view and I didn't need to register them like that to make it work two ways. For some reason on the TabControl I had to register the property like I did above.

    Hope this help someone else.

    Turns out my problem were because my components have names:

    x:Name="xxxxxxxx"
    

    Giving names to components at the same time of biding them with DependencyObject seems to be the main cause of all my issues.

提交回复
热议问题