Ned
Ned

Reputation: 4141

Get element inside a DataTemplate

I have a following XAML and I need to change visibility of imageRemoveButton at runtime from the code behind file. How do I access that button?

<ItemsControl x:Name="ImagesItemsControl">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Border BorderBrush="#ffdddddd"
                    BorderThickness="0,0,0,1">
                <Grid Margin="0,2">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="15" />
                        <ColumnDefinition />
                        <ColumnDefinition Width="20" />
                    </Grid.ColumnDefinitions>

                    <Grid Grid.Column="1"
                          VerticalAlignment="Center">
                        <TextBlock Text="{Binding Name}"
                                      TextWrapping="Wrap" />
                    </Grid>
                    <Button Grid.Column="3"
                            Width="20"
                            Height="20"
                            Content="X"
                            Template="{StaticResource ButtonAddTab}"
                            Style="{StaticResource ButtonWizard}"
                            Tag="{Binding}"
                            x:Name="imageRemoveButton"
                            Click="ImageRemoveButton_Click" />
                </Grid>
            </Border>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

Upvotes: 2

Views: 1990

Answers (3)

matt
matt

Reputation: 19

Use the loaded event on the button to save a reference to the button in the cs file. Use this reference when needed to change the visibility.

Upvotes: 1

Adriaan Davel
Adriaan Davel

Reputation: 748

Try using Source binding to a class that will manage the button's visibility state. Adding a property to all your data items would be painfull but could be required if the button's visibility needs to be set based on a property of your data item. As per standard MVVM patterns you can then control the button's visibility from C#. If you need a specific instance of the button you can add a Loaded event handler to it and cache it accordingly.

Upvotes: 0

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93561

You cannot reference-by-name elements in a template. There is no matching code-behind/designer property generated by templates.

You want to bind the visibility of a control in the template to a property of your data items. That means you will need to add a property to your data items. Can you provide more details of your data items? If the property is a bool value, use a VisibilityConvertor (dime a dozen on this site).

Think of templates as wanting to always pull settings from the bindings, rather than have settings stuffed into them from the outside.

Upvotes: 0

Related Questions