WP7:为什么 ListBox.ItemsPanel 会破坏我的 ElementName 数据绑定?
我有一个绑定到整数列表的 Windows Phone 7 ListBox
。我使用的是默认的 MVVM Light 模板,因此有一个包含数据和简单的 RelayCommand 的 ViewModel 类。这是列表框:
<ListBox ItemsSource="{Binding MyData}">
<ListBox.ItemTemplate>
<DataTemplate>
<Button Content="{Binding}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<cmd:EventToCommand Command="{Binding ElementName=ContentGrid, Path=DataContext.TestCommand}"
CommandParameter="{Binding}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
它显示按钮内整数的垂直列表。如果单击其中任何一个,则会执行以下命令代码并显示弹出窗口: new RelayCommand
但是,如果我只是添加以下 XAML 来更改为水平列表,则数据绑定会失败。单击该按钮时不会发生任何事情,并且不会将错误消息写入“输出”窗口。
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center" />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
我尝试了 EventToCommand
的一些其他类型的绑定。例如,将我的 ViewModel
指定为静态资源。它可以工作,但不如上面的示例理想。
为什么 ItemsPanel
会破坏数据绑定?
I have a Windows Phone 7 ListBox
that binds to a list of integers. I am using the default MVVM Light template, so there is a ViewModel
class that contains data and a simple RelayCommand
. Here is the ListBox:
<ListBox ItemsSource="{Binding MyData}">
<ListBox.ItemTemplate>
<DataTemplate>
<Button Content="{Binding}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<cmd:EventToCommand Command="{Binding ElementName=ContentGrid, Path=DataContext.TestCommand}"
CommandParameter="{Binding}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
This displays a vertical list of integers inside buttons. If you click any of them, the following command code executes and shows a pop-up: new RelayCommand<int>(i => MessageBox.Show("Test" + i));
However, if I simply add the following XAML to change to a horizontal list, the databinding fails. Nothing happens when you click the button and no error messages are written to the Output window.
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center" />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
I have tried some other types of binding for the EventToCommand
. For example, specifying my ViewModel
as a static resource. It works, but is less ideal than the example above.
Why does that ItemsPanel
break the databinding?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是
Silverlight 3
的一个已知问题。要解决此问题,请将您的DataTemplate
包装在UserControl
中:并使用它:
This is a known problem with
Silverlight 3
. To work around this, wrap yourDataTemplate
in aUserControl
:And use it instead: