作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有 Windows Phone 7 ListBox
绑定(bind)到整数列表。我使用的是默认的 MVVM Light 模板,所以有一个 ViewModel
包含数据和简单 RelayCommand
的类.这是列表框:
<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<int>(i => MessageBox.Show("Test" + i));
但是,如果我简单地添加以下 XAML 以更改为水平列表,则数据绑定(bind)会失败。单击按钮时没有任何反应,也没有错误消息写入输出窗口。
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center" />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
我已经为 EventToCommand
尝试了一些其他类型的绑定(bind).例如,指定我的 ViewModel
作为静态资源。它有效,但不如上面的示例理想。
为什么会这样 ItemsPanel
打破数据绑定(bind)?
最佳答案
这是 Silverlight 3
的一个已知问题。要解决此问题,请将您的 DataTemplate
包装在 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>
关于c# - WP7 : Why does a ListBox. ItemsPanel 打破了我的 ElementName 数据绑定(bind)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4640370/
我是一名优秀的程序员,十分优秀!