Search code examples
wpfmvvmbindingeventtriggerevent-binding

MVVM WPF: Reflecting a controls property to the viewmodel, when an events get triggered


Okay i'm trying to understand WPF and the popular MVVM Pattern.

Now i have this issue. I'm using a ribbon control with several tabs. In my ViewModel i have a property "ActiveTab (string)" Which should reflect the currently active tab.

Since ribboncontrol doesn't have any property that shows this information i can't bind to it.

So i was thinking:

I could bind the selected event like this:

        <r:RibbonTab Label="tab1" Selected="RibbonTab_Selected"></r:RibbonTab>
        <r:RibbonTab Label="tab2" Selected="RibbonTab_Selected"></r:RibbonTab>
        <r:RibbonTab Label="tab3" Selected="RibbonTab_Selected"></r:RibbonTab>
        <r:RibbonTab Label="tab4" Selected="RibbonTab_Selected"></r:RibbonTab>
        <r:RibbonTab Label="tab5" Selected="RibbonTab_Selected"></r:RibbonTab>

Then in codebehind set the property in the viewmodel by using Activetab = sender.Label

But Then i would need a refference to my viewmodel in the codebehind of my view.

I'm trying to solve this problem without using any code behind files. (MVVM).

Now the real question: Is it somehow possible to use an eventtrigger or eventsetter. that when the selected event gets fired. A setter automaticly sets the activetab property to the sender.Label value?.

Using xaml only.

-- My excuses for my rather bad english and maybe noobish question. I'm very new at wpf =)


UPDATE: As i just found out, there is a isSelected property on a ribbonTab.

Now i have some issues on how to bind it to the property in my viewmodel.

I tried the following code:

<Style TargetType="{x:Type r:RibbonTab}">
                <Style.Triggers>
                    <Trigger Property="IsSelected" Value="True">
                        <Setter Property="{Binding SelectedTab}" Value="{Binding RelativeSource=Self, Path=Label}" />
                    </Trigger>
                </Style.Triggers>
            </Style>

But this doesn't work:

Error   1   Cannot find the Style Property 'SelectedTab' on the type 'Microsoft.Windows.Controls.Ribbon.RibbonTab'. 

SelectedTab offcourse is in my viewmodel and not in ribbonTab ...

How can i make the setter, set the property on my viewmodel with the value of the tab? =)

Thanks in advance!!


Solution

  • The August release of the Microsoft Ribbon, the RibbonTab has a IsSelected dependency property, so you should be able to bind to that.