I'm building a Windows Universal application where I need to put some elements on a canvas. Since I want to do this MVVM style I've read that I should use an ItemsControl for it. Problem is that all the solutions I found are for WPF or Silverlight and don't work for Windows Universal. They appear on the canvas, but they keep positioning themselfs in the left upper corner.
XAML:
<ItemsControl ItemsSource="{Binding MyItems}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Text}" FontSize="18"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemContainerStyle>
<Style TargetType="ContentPresenter">
<Setter Property="Canvas.Left" Value="{Binding Left}" />
<Setter Property="Canvas.Top" Value="{Binding Top}" />
</Style>
</ItemsControl.ItemContainerStyle>
</ItemsControl>
XAML's code behind:
public MainPage()
{
this.InitializeComponent();
DataContext = new MyItemViewModel();
}
Viewmodel and model:
class MyItemViewModel
{
ObservableCollection<MyItem> _myItems;
public MyItemViewModel()
{
_myItems = new ObservableCollection<MyItem>();
_myItems.Add(new MyItem(10, 10, "First TextBlock"));
_myItems.Add(new MyItem(200, 400, "2nd TextBlock"));
_myItems.Add(new MyItem(400, 200, "The Third TextBlock"));
}
public ObservableCollection<MyItem> MyItems
{
get { return _myItems; }
set { _myItems = value; }
}
}
public class MyItem
{
public MyItem(double left, double top, string text)
{
Left = left;
Top = top;
Text = text;
}
public double Left { get; set; }
public double Top { get; set; }
public string Text { get; set; }
}