我有一个列表框绑定到名为Choices的视图模型属性。每个选项都有一个标签和一个索引。我需要将列表中的按钮绑定到同一视图模型上的命令。到目前为止,我已经找到了这么多:
<ListBox Grid.Row="1" ItemsSource="{Binding Choices}" SelectedIndex="{Binding SelectedChoice, Mode=TwoWay}" >
<ListBox.ItemTemplate>
<DataTemplate>
<Grid HorizontalAlignment="Stretch" Margin="1">
<Button Content="{Binding Caption}" Height="24" HorizontalAlignment="Stretch"
Command="{Binding RelativeSource={RelativeSource ???},
Path=SelectChoice}" CommandParameter="{Binding}"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
我无法弄清楚用于命令的RelativeSource是什么,我不确定CommandParameter是否正确。
这似乎是一件非常简单的事情,但对于我可怜的老脑来说,这显然太简单了。有人可以帮忙吗?
由于
答案 0 :(得分:2)
排序:
<ItemsControl Grid.Row="1" ItemsSource="{Binding Choices}" >
<ItemsControl.ItemsPanel >
<ItemsPanelTemplate >
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
</StackPanel>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Content="{Binding Caption}" Height="24" HorizontalAlignment="Stretch" Margin="0,0,4,0"
Command="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ItemsControl}}, Path=DataContext.SelectChoice}"
CommandParameter="{Binding}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>