gpt4 book ai didi

c# - WP7 : Why does a ListBox. ItemsPanel 打破了我的 ElementName 数据绑定(bind)?

转载 作者:行者123 更新时间:2023-11-30 17:19:44 26 4
gpt4 key购买 nike

我有 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/

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