gpt4 book ai didi

binding - 如何在 WinRT 中的 ItemContainerStyle 中进行绑定(bind)?

转载 作者:行者123 更新时间:2023-12-03 11:01:19 24 4
gpt4 key购买 nike

我正在尝试将集合绑定(bind)到 ItemsControl,将 Canvas 作为项目面板,并将每个项目的 Canvas.Left 和 Top 绑定(bind)到项目对象的属性。基本上我正在尝试重新创建我在 this post on my blog 中描述的二维数据绑定(bind)。 ,但这次是在 WinRT 而不是 WPF 中。

由于 ItemsControl 将您的 ItemTemplate 内容包装在另一个 UI 元素(在 WinRT 的情况下为 ContentPresenter)中,并且这些包装器/容器元素直接放置在项目面板内,因此必须在这些容器上设置 Left 和 Top;您不能只在 DataTemplate 中设置它们。在 WPF 中,使用 ItemContainerStyle 中的绑定(bind)很容易做到这一点,例如:

<ItemsControl.ItemContainerStyle>
<Style>
<Setter Property="Canvas.Left" Value="{Binding Path=X}"/>
<Setter Property="Canvas.Top" Value="{Binding Path=Y}"/>
</Style>
</ItemsControl.ItemContainerStyle>

但是当我在 WinRT/XAML 项目中尝试同样的事情时,我什么也得不到。甚至没有绑定(bind)错误。如果我硬编码一个值,它会起作用;但如果我使用绑定(bind),该属性将保持其默认值(零),并且“输出”窗口中不会显示任何绑定(bind)错误。
<ItemsControl.ItemContainerStyle>
<Style TargetType="ContentPresenter">
<!-- This works, so ItemContainerStyle does work in WinRT: -->
<Setter Property="Canvas.Left" Value="200"/>
<!-- But this silently fails, leaves Top as 0, and does not show
any binding errors in the debugger's Output window: -->
<Setter Property="Canvas.Top" Value="{Binding Y}"/>
</Style>
</ItemsControl.ItemContainerStyle>

我已经验证 ContentPresenters 确实具有正确的 DataContext(即集合项,而不是集合本身或其他时髦的东西),所以您认为这些绑定(bind)可以正常工作。但他们似乎甚至没有得到评估。如果我在其他任何地方放置了错误的绑定(bind)并运行调试构建,我会在调试器的输出窗口中看到绑定(bind)错误;但是如果我在我的 ItemContainerStyle 中引用了一个无意义的属性,则不会显示绑定(bind)错误。

这是一个更完整的示例,(据我所知)在 WPF 中应该可以正常工作,但是在 WinRT 中将所有内容留在原点:
<ItemsControl ItemsSource="{Binding Tiles}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemContainerStyle>
<Style TargetType="ContentPresenter">
<Setter Property="Canvas.Left" Value="{Binding DataContext.Left}"/>
</Style>
</ItemsControl.ItemContainerStyle>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Rectangle Width="80" Height="80" Fill="Gray"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>

我在 Binding 上尝试了一些更奇特的选项。 -- 特别是 RelativeSource .当我使用 RelativeSource TemplatedParent ,无所事事的行为没有改变。但是,当我使用 RelativeSource Self ,我确实得到了一个绑定(bind)错误,说该属性在类型 Setter 上不存在!它正在采取 Self有点太字面意思了。

我也玩过 TemplateBinding ,但我从来没有真正理解过它的用途,我得到的只是一些难以理解的 COM 错误(欢迎使用 WinRT,这是一个巨大的技术倒退)。

我怎样才能 (a) 使绑定(bind)正常工作( Binding 上是否有其他选项可以用来强制它正常工作?),或者 (b) 以其他方式允许我的 ItemsContainer 中的项目在 Canvas 上任意定位基于对集合项属性的数据绑定(bind)?

最佳答案

Setter 不支持绑定(bind)。我认为 Silverlight 仅在版本 5 中获得了它们。对于解决方法,您可以查看我的旧文章 here .基本上,您定义一个附加的依赖属性,为您设置绑定(bind)。

关于binding - 如何在 WinRT 中的 ItemContainerStyle 中进行绑定(bind)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11857505/

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