【发布时间】:2016-03-25 03:10:43
【问题描述】:
我正在构建一个 Windows 通用应用程序,我需要将一些元素放在画布上。因为我想做这种 MVVM 风格,所以我读过我应该使用 ItemsControl 。问题是我找到的所有解决方案都适用于 WPF 或 Silverlight,不适用于 Windows Universal。它们出现在画布上,但始终位于左上角。
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 背后的代码:
public MainPage()
{
this.InitializeComponent();
DataContext = new MyItemViewModel();
}
视图模型和模型:
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; }
}
【问题讨论】:
-
我不同意。我看到了这些项目,但他们没有例外。他们只是停留在左上角。
-
我认为您的
TargetType是错误的。试试这个:TargetType="{x:Type UIElement}"。如果这不起作用,请尝试完全删除TargetType属性。 -
经过简短的搜索后,似乎 Windows Universal 应用程序可能不支持这种类型的样式绑定(该问题实际上可以追溯到 WinRT 和之前的 Silverlight)。请参阅this SO answer 和this one。
标签: c# xaml canvas mvvm win-universal-app