Hi,
How would I be able to set the tag member of a ListBoxItem inside a datatemplate? I am databinding a ListBox and I am trying to add information to the ListBoxItem.Tag from my DataContext. I am using A DataTemplate to display the ListBoxItem.
Hi,
How would I be able to set the tag member of a ListBoxItem inside a datatemplate? I am databinding a ListBox and I am trying to add information to the ListBoxItem.Tag from my DataContext. I am using A DataTemplate to display the ListBoxItem.
Instead of setting the Tag in the DataTemplate for your items, you should look at setting it through a style. We can apply both a style and a template to our items, and they won't interfere with each other. Because our items are going to be inside of a ListBox, they will automatically be wrapped in a ListBoxItem, and we can target that type with our style.
Here we're applying some DataTemplate to the items (defined somewhere as a resource) and using a Style to set the Tag Value for each item in this ListBox.
<ListBox ItemsSource="{Binding MyItems}" ItemTemplate="{StaticResource MyDataTemplate}">
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Tag"
Value="It has a Tag" />
</Style>
</ListBox.ItemContainerStyle>
</ListBox>