gpt4 book ai didi

c# - 使用 Canvas 在 ItemsControl 上定位 XAML UI 元素

转载 作者:太空宇宙 更新时间:2023-11-03 17:00:57 28 4
gpt4 key购买 nike

我正在构建一个 Windows 通用应用程序,我需要在其中将一些元素放在 Canvas 上。因为我想做这种 MVVM 风格,所以我读过我应该为它使用 ItemsControl。问题是我找到的所有解决方案都适用于 WPF 或 Silverlight,不适用于 Windows Universal。它们出现在 Canvas 上,但始终位于左上角。

Current result

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();
}

View 模型和模型:

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; }
}

最佳答案

改为使用 FrameworkElement 作为 TargetType:

<ItemsControl.ItemContainerStyle>
<Style TargetType="FrameworkElement">
<Setter Property="Canvas.Left" Value="{Binding Left}" />
<Setter Property="Canvas.Top" Value="{Binding Top}" />
</Style>
</ItemsControl.ItemContainerStyle>

关于c# - 使用 Canvas 在 ItemsControl 上定位 XAML UI 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34355105/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com