Home > Net >  Trying to add the objects to my canvas but the function of mycanvas.children.add() doesnt work,any o
Trying to add the objects to my canvas but the function of mycanvas.children.add() doesnt work,any o

Time:05-31

I tried it with rectangles and it worked but i need to work with the piece which is

important for my clasess because they inherits from him. how do i add the objects to my canvas

if they are not rectangle?

public sealed partial class MainPage : Page
{
    System.Collections.Generic.List<Piece> arr_Enemy = new System.Collections.Generic.List<Piece>();
    public MainPage()
    {
        this.InitializeComponent();
        Player _player = new Player(50,80, 50, 50, new BitmapImage(new Uri("ms-appx:///Assets/Background.jpg")));
        MyCanvas.Background = new ImageBrush
        {
            ImageSource = new BitmapImage(new Uri("ms-appx:///Assets/Background.jpg"))
        };
        MyCanvas.Children.Add(_player);
        for (int i = 0; i < arr_Enemy.Count; i  )
        {
            arr_Enemy[i] = new Piece(rnd.Next(250), rnd.Next(500), 150, 120, new BitmapImage(new Uri("ms-appx:///Assets/enemy.GIF")));
            MyCanvas.ChildrenTransitions.Add(arr_Enemy[i])
        }
    }
}

CodePudding user response:

You can only add UIElements to the Children collecton of a Canvas just like you can only add strings to a List<string> for example.

If you Player is some kind of control, it should inherit from UIElement.

If Player is some kind of model, you could use an ItemsControl with a Canvas panel to display the models in your view:

<ItemsControl x:Name="ic" ItemsSource="{x:Bind ListOfPlayers}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <Canvas />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate x:DataType="{x:Bind local:Player}">
            <TextBlock Text="I'm a player..." />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

You would then add the players to the ListOfPlayers source collection.

  • Related