Binding and WPF Styles with MVVM

I have a problem with data binding to a style in WPF.

The basic setup is as follows:

<Style x:Key="{x:Type eo:Player}" TargetType="{x:Type eo:Player}">
        <Style.Triggers>
            <DataTrigger Binding="{Binding Team}" Value="A">
                <Setter Property="Template" Value="{StaticResource TeamATemplate}"></Setter>
            </DataTrigger>
        </Style.Triggers>
</Style>

The style applies to all objects of type Player. These objects have a property of type "Commands" (Enum, which has values ​​A, B and C). Depending on which player’s team is in the template used for visualization, the player is different.

The problem that now arises is that all this is used in the MVVM application and that somehow the Player's DataContext is set in the ViewModel of the topmost view. I used the new diagnostic options (TraceLevel) to find out something about the problem, and received the following:

System.Windows.Data Warning: 66 : BindingExpression (hash=30607723): Found data context element: Player (hash=35170261) (OK)
System.Windows.Data Warning: 74 : BindingExpression (hash=30607723): Activate with root item ToolboxViewModel (hash=61398511)
System.Windows.Data Warning: 104 : BindingExpression (hash=30607723):   At level 0 - for ToolboxViewModel.Team found accessor <null>

, Player ( ), ToolboxViewModel DataContext. ? ?

+3
2

, :

<Style x:Key="{x:Type eo:Player}" TargetType="{x:Type eo:Player}">
        <Style.Triggers>
                <DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Path=Team}" Value="A">
                        <Setter Property="Template" Value="{StaticResource TeamATemplate}"></Setter>
                </DataTrigger>
        </Style.Triggers>
</Style>

{RelativeSource Self}

+3

- , . :

<Style x:Key="{x:Type eo:Player}" TargetType="{x:Type eo:Player}">
        <Setter Property="Template" Value="{StaticResource TeamBTemplate" />
        <Style.Triggers>
                <DataTrigger Binding="{Binding Team}" Value="A">
                        <Setter Property="Template" Value="{StaticResource TeamATemplate}"></Setter>
                </DataTrigger>
        </Style.Triggers>
</Style>

, . .

-1

Source: https://habr.com/ru/post/1718705/


All Articles