Danial
Danial

Reputation: 108

"Canvas" methods doesn't work in itemsControl

Canvas methods always work when they are in a canvas tag, but When you tryna use them in an itemsControl, they sometimes stop working. here's an example:

<ItemsControl>
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <Canvas />
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Button Click="Button_Click">Text</Button>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
   
    </ItemsControl>

xaml.cs file

private void Button_Click(object sender, RoutedEventArgs e)
    {
        MessageBox.Show(Canvas.GetTop(sender as Button).ToString());
    }

Here messagebox returns Nan and I don't know the reason. You can't use SetTop or left method either. Can you help?

Edit: Here's another interesting thing if I give a name to an element it does work, but I don't want that because the names aren't available in the itemTemplate.

here's the code:

 <ItemsControl ItemsSource="{Binding SomeList}">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <Canvas />
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
   <Button x:Name="Btn" Click="Button_Click">Text</Button>
   
    </ItemsControl>

xaml.cs file

 private void Button_Click(object sender, RoutedEventArgs e)
    {
        MessageBox.Show(Canvas.GetTop(Btn).ToString());
    }

Upvotes: -2

Views: 63

Answers (1)

mm8
mm8

Reputation: 169200

To position define the absolute position of the element in the ItemTemplate, you should bind the Canvas.Top attached property of the container to a property of the type of objects in the SomeList collection:

<ItemsControl ItemsSource="{Binding SomeList}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <Canvas />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemContainerStyle>
        <Style TargetType="ContentPresenter">
            <Setter Property="Canvas.Top" Value="{Binding Top}" />
        </Style>
    </ItemsControl.ItemContainerStyle>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Button Click="Button_Click">Text</Button>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

SomeList should be an IEnumerable<T> where the type T has a Top property of type double:

public class Item
{
    public double Top { get; set; }
}

Upvotes: 1

Related Questions