【发布时间】:2011-06-13 13:56:58
【问题描述】:
我正在尝试为我的应用程序创建一个菜单栏。我在 xaml 中创建了一个集合,其中包含我的菜单将绑定到的菜单项。
在 xaml 中,我创建了一个数组,用作绑定的静态资源。
<coll:ArrayList x:Key="MenuOptionsList">
<model:DashboardMenuBarItem
Icon="the location of an image in my images folder"
DisplayName="The test that will appear under my button"
CommandName="someCommandInMyViewModel"/>
</coll:ArrayList>
我正在使用带有数据模板的列表框来显示这些项目,如下所示。
<ListBox x:Name="lstNavigateTo" MinWidth="400" DockPanel.Dock="Top"
ItemsSource="{Binding Source={StaticResource MenuOptionsList}}"
ScrollViewer.HorizontalScrollBarVisibility="Disabled"
Style="{StaticResource horizontalListTemplate}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Margin="5">
<Button Height="60" Width="60"
Command="{Binding Mode=OneWay, Path=CommandName}">
<Button.Content>
<Image Source="{Binding Path=Icon}" Grid.Row="0" />
</Button.Content>
</Button>
<TextBlock Text="{Binding Path=DisplayName}"
Width="100" TextAlignment="Center" Grid.Row="1" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
我的问题是我使用的是 MVVM 设计模式,无法让命令绑定在按钮单击时起作用。以前我会像这样管理按钮点击。
Command="{Binding someCommandInMyViewModel}"
这可以正常工作,但是当我尝试将命令绑定到我的集合中某个项目的属性时,该命令不会触发。
有谁知道我如何做到这一点。
【问题讨论】:
-
模板绑定的其余部分是否有效,即您的图标和文本都正确显示?另外,您的命令是否支持 CanExecute,如果支持,按钮是否会亮起?
-
除命令绑定外,其他一切都有效。我可以看到按钮及其图像,但没有任何功能。我相信@Kent Boogaart 一针见血。我还没有足够的 MVVM 和命令绑定经验来做我想做的事情,尤其是构建一个转换器来将字符串更改为 ICommand。
-
您需要做的第一件事是打开数据绑定的调试消息:i.imgur.com/UAxJO.png 接下来,重新运行并检查输出窗口,看看有什么错误。其次,你做错了。不,这有点苛刻......你这样做奇怪。