Binding to a method with parameter in XAML using polymorphism in ViewModel

后端 未结 3 1824
花落未央
花落未央 2021-02-20 09:34

I have a TabControl with six tabs in my ResultView. The ViewModel that sits behind this View can be either a ResultTypeOneViewModel or ResultTypeTwoViewModel, each of which deri

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-20 09:47

    You can use an indexer property to be able to pass a single parameter to a property. Although it's probably not very intuitive to return a boolean value from an indexer property it works fine for me. Also keep in mind the indexer property looses it's expected functionality.

        class MyClass
        {
            public bool this[int tabNumber]
            {
                get
                {
                    // Do logic to determine visibility here or in a separate method
                    return IsTabVisible(tabNumber);
                }
            }
    
            bool IsTabVisible(int tabNumber)
            {
                bool result;
    
                // Method logic...
    
                return result;
            }
        }
    

    So in XAML you can use the class name and provide a parameter between square brackets.

    
    

    If you need to raise a NotifyPropertyChanged for the indexer property use:

        NotifyPropertyChanged("Item[]");
    

    I don't know if this fits into the MVVM pattern but it could be useful for anyone who wants to bind to a method with a single parameter.

提交回复
热议问题