Reputation: 12814
I'd like to bind to a element's property (a ListBox's SelectedItems.Count
in my specific case) that's dynamically inserted into my window from a DataTemplate
located in a ResourceDictionary
. I'd like to enable/disable a button when the count reaches a certain number of ListBoxItems
are selected. I thought this would work:
<Style TargetType="Button">
<Style.Triggers>
<DataTrigger Binding="{Binding Source={StaticResource myResourceKey}, Path=myListBox.SelectedItems.Count}" Value="25">
<Setter Property="IsEnabled" Value="False"/>
</DataTrigger>
</Style.Triggers>
</Style>
But I'm getting the following error:
System.Windows.Data Error: 40 : BindingExpression path error: 'myListBox' property not found on 'object' ''DataTemplate' (HashCode=50217655)'. BindingExpression:Path=aoiListBox.SelectedItems.Count; DataItem='DataTemplate' (HashCode=50217655); target element is 'Button' (Name='myBtn'); target property is 'NoTarget' (type 'Object')
How can I achieve this binding? Thanks in advance.
Upvotes: 1
Views: 1539
Reputation: 4865
Well you can write a workaround, but I strongly recomment not to implement it that way. Consider, that a style in a ResourceDictionary
is an empty resource, which should be decoupled from any specific instance (in your case myListBox
) in your application. Problem is, that you cannot use this malformed style on another Button
. So you don't need to, better you shouldn't, declare it as resource.
I definitely recomment to declare this Style
directly in the Button
. E.g.
<ListBox x:Name="myListBox" />
<Button>
<Button.Style>
<Style TargetType="Button">
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=myListBox,
Path=SelectedItems.Count}" Value="25">
<Setter Property="IsEnabled" Value="False"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
Additionally, I would use a Binding
via the ElementName
property.
Upvotes: 1