user1702369 user1702369 -4 years ago 109
C# Question

How to access ElementName of Dynamic controls

I have an ItemsControl which have dynamically created Buttons

<ItemsControl>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button>
</Button>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>


I am trying to display a Popup when hovering over one of these buttons, but seeing that the buttons are generic, I dont know the name of the button. Like this:

<Popup PlacementTarget="{Binding ElementName=buttonName}"
IsOpen ="{Binding IsMouseOver, ElementName=buttonName, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}">


How can I achieve opening the Popup and set the PlacementTarget of the Button I'm hovering over??

Answer Source

Simply place popup inside datatemplate as well:

<ItemsControl>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Grid>
                <Button x:Name="buttonName"/>
                <Popup PlacementTarget="{Binding ElementName=buttonName}" IsOpen="{Binding IsMouseOver, ElementName=buttonName, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" />
            </Grid>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download