【问题标题】:Positioning XAMLUI elements on ItemsControl with Canvas使用 Canvas 在 ItemsControl 上定位 XAMLUI 元素
【发布时间】: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 answerthis one

标签: c# xaml canvas mvvm win-universal-app


【解决方案1】:

改用FrameworkElement 作为TargetType

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

【讨论】:

  • 不使用就无法编译
  • 我的错,我以为你在使用 WPF。尝试添加 FrameworkElement 的目标类型。
猜你喜欢
  • 1970-01-01
  • 2020-08-22
  • 1970-01-01
  • 2013-02-02
  • 2014-02-22
  • 2012-06-04
  • 2012-09-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多