Reputation: 3117
I have a problem with databinding on a style in WPF.
The basic setup looks like this:
<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 is applied to all objects of type Player. These objects have a property of type Teams (Enum having values A, B and C). Depending on which team the player is in the template applied to visualize the player differs.
The problem that now occurs is that the whole thing is used in a MVVM application and that somehow the DataContext of the Player object gets set to the ViewModel of the topmost View. I used the new diagnostics options (TraceLevel) to find out something about the problem and got this:
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>
So basically the Player object is found as a data context element (whatever that means) but still the ToolboxViewModel is used as DataContext. How can I fix this? How can I refer to the styled object in the binding expression?
Upvotes: 2
Views: 5408
Reputation: 3117
I don't know why I didn't think of this earlier:
<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>
It works perfectly fine with {RelativeSource Self}
Upvotes: 2
Reputation: 25640
You cant' style anything with a trigger that you haven't styled with your style already. You'll need to do this:
<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>
Seems like your style should work after this. Those binding warnings are confusing though.
Upvotes: -1