我有一个ItemsControl,基本上是一组组合框,文本框和按钮:
该底部的XAML都在ItemsControl中:(按钮有问题,最后一个元素)
<ItemsControl Grid.Row="2"
ItemsSource="{Binding CommandLinesOc}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Vertical" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Label Content="Send Command:"
HorizontalAlignment="Right"
Grid.Row="1" />
<ComboBox Grid.Column="1"
Grid.Row="1"
ItemsSource="{Binding ChromaCommandsCvs.View}"
SelectedItem="{Binding SelectedChromaCommand, UpdateSourceTrigger=PropertyChanged}" />
<Label Grid.Column="2"
Grid.Row="1"
Content="Parameter:"
HorizontalAlignment="Right" />
<TextBox Grid.Column="3"
Grid.Row="1"
Text="{Binding Parameter, UpdateSourceTrigger=PropertyChanged}" />
<Button Grid.Column="4"
DataContext="ChromaGUI.MainWindow"
Grid.Row="1"
Content="Send"
HorizontalAlignment="Center"
FontSize="15"
Command="{Binding RelativeSource=
{RelativeSource Mode=FindAncestor,
AncestorType={x:Type Window}},
Path=DataContext.SendMessageCommand}"
CommandParameter="{Binding FullCommandString}"/>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
如您所见,我已将按钮元素绑定到relay命令。我不得不使用主窗口相对源,因为ItemsControl正在将数据上下文设置为CommandLinesOc中的项目。
一切正常 - 问题是CommandParameter似乎继承了相同的相对源上下文,因为我无法获得FullCommandString(或者可观察集合中某个项的任何其他属性,如Parameter或SelectedChromaCommand)解决任何问题。所以我的问题是,我可以(以及如何)将CommandParameter的数据上下文设置为ItemsControl给我的内容,同时保持Command的上下文为父窗口?
答案 0 :(得分:1)
目前,您将按钮DataContext
设置为字符串“ChromaGUI.MainWindow”:
<Button DataContext="ChromaGUI.MainWindow"
.......
Command="{Binding RelativeSource=
{RelativeSource Mode=FindAncestor,
AncestorType={x:Type Window}},
Path=DataContext.SendMessageCommand}"
CommandParameter="{Binding FullCommandString}"/>
String没有属性FullCommandString
,因此命令参数绑定将失败。只需删除按钮中的DataContext
设置,即可使用默认DataContext
,这是ItemsSource
中对应的项目:
<Button
.......
Command="{Binding RelativeSource=
{RelativeSource Mode=FindAncestor,
AncestorType={x:Type Window}},
Path=DataContext.SendMessageCommand}"
CommandParameter="{Binding FullCommandString}"/>