Unique name for element inside of Listbox

By : m0ngr31
Source: Stackoverflow.com
Question!

I'm running into a problem where I need to name a UIElement inside of a ListBox, but I can't because it's going to be looping through and obviously can't have a million little TextBlock's running around with the same name.

Here's my a simplified version of my ListBox:

<ListBox Background="Transparent">
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Setter Property="HorizontalContentAlignment" Value="Stretch" />                            
        </Style>
    </ListBox.ItemContainerStyle>
    <ListBox.ItemTemplate>
       <DataTemplate>
            <RelativePanel">
                <TextBlock FontSize="12" Text="{Binding Path=Hub}" FontWeight="Bold" Name="firstText" />
                <TextBlock FontSize="12" Text="{Binding Path=Stats.Pages}" Name="secondText" RelativePanel.RightOf="firstText" />
                <VisualStateManager.VisualStateGroups>
                    <VisualStateGroup>
                        <VisualState>
                            <VisualState.StateTriggers>
                                <AdaptiveTrigger MinWindowWidth="1100" />
                            </VisualState.StateTriggers>
                            <VisualState.Setters>
                                <Setter Target="secondText.(RelativePanel.RightOf)" Value="hubText" />
                            </VisualState.Setters>
                        </VisualState>
                        <VisualState>
                            <VisualState.StateTriggers>
                                <AdaptiveTrigger MinWindowWidth="0" />
                            </VisualState.StateTriggers>
                            <VisualState.Setters>
                                <Setter Target="secondText.(RelativePanel.Below)" Value="firstText" />
                            </VisualState.Setters>
                        </VisualState>
                    </VisualStateGroup>
                </VisualStateManager.VisualStateGroups>
            </RelativePanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

For my situation I'm trying to use AdaptiveTriggers on the RelativePanel to set the positioning of the secondText TextBlock to the right of firstText when there is a wider screen, and underneath when there is a smaller screen.

As far as I know, the only way I can change this is using the Setter on the name, so I'd need a unique one somehow? Is there a better way to do this?

EDIT: Okay, so it compiled and ran fine (RelativePanel.RightOf is working initially), but the AdaptiveTriggers don't work, and VS is throwing a tissy about the markup. What can I do?

By : m0ngr31


Answers

The trick is to wrap the elements inside your DataTemplate with a UserControl.

By : Justin XL


This video can help you solving your question :)
By: admin