WP7:为什么一个ListBox.ItemsPanel打破我的ElementName数据绑定? [英] WP7: Why does a ListBox.ItemsPanel break my ElementName data binding?
问题描述
我有一个Windows Phone 7的的ListBox
结合整数列表。我使用的是默认的MVVM光模板,所以有一个视图模型
类包含数据和一个简单的 RelayCommand
。这里是列表框:
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>
这里面显示的按钮整数垂直列表。如果你点击其中任何一个,以下命令代码执行,并显示一个弹出:新RelayCommand< INT>(I => MessageBox.Show(测试+ I));
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));
不过,如果我只是添加下面的XAML更改为水平列表,数据绑定失败。当你单击该按钮并没有错误消息被写入到输出窗口什么也没有发生。
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>
我曾尝试为 EventToCommand $ C结合一些其他类型$ C>。例如,指定我
视图模型
作为静态的资源。它的工作原理,但比上面的例子不太理想。
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.
为什么说 ItemsPanel
打破绑定?
推荐答案
这是一个已知的问题与 Silverlight 3的
。要解决这个问题,换你的的DataTemplate
在用户控件
:
This is a known problem with Silverlight 3
. To work around this, wrap your DataTemplate
in a UserControl
:
<UserControl x:Class="SilverlightApplication.MyUserControl">
<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>
</UserControl>
和使用它来代替:
<ListBox ItemsSource="{Binding MyData}">
<ListBox.ItemTemplate>
<DataTemplate>
<local:MyUserControl />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
这篇关于WP7:为什么一个ListBox.ItemsPanel打破我的ElementName数据绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!