我有一个带有可扩展标题的列表视图,这可以正常工作,但是当我在其中添加一个按钮时,它不会触发相关的命令。
<ControlTemplate>
<Expander IsExpanded="True">
<Expander.Header>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}" Name="txtX" FontWeight="Bold" Foreground="Gray" FontSize="22" VerticalAlignment="Bottom" />
<Button Content="Add Task List" Width="150" HorizontalAlignment="Right" Command="{Binding XCommand}"/>
</StackPanel>
</Expander.Header>
<ItemsPresenter />
</Expander>
</ControlTemplate>
页面上的所有其他按钮都会正确地向我的viewmodel发出命令,所以我会冒险猜测它是与xaml相关的东西,或者是每个分组动态创建按钮的方式。
*的修改
只需为上下文添加一些相关的视图模型代码。如果我在listview之外添加一个相同的按钮,它会触发命令。 A link to an image of the whole xaml.
#Region "Properties"
Public Property XCommand As ICommand
#End Region
#Region " Constructors"
Public Sub New(ByVal regionManager As IRegionManager, _
ByVal container As IUnityContainer)
XCommand = New RelayCommand(AddressOf DoSomething)
_regionManager = regionManager
_container = container
End Sub
#End Region
#Region "Command methods"
Private Sub DoSomething()
MessageBox.show("Test")
End Sub
#End Region
有关如何使其正常工作的任何帮助?
三江源!
答案 0 :(得分:2)
当您在GroupItem
样式内绑定时,您将绑定到GroupItem
的数据上下文。您需要绑定到视图模型(ListView的数据上下文)。您可以使用RelativeSource
:
<Button Command="{Binding DataContext.XCommand, RelativeSource={RelativeSource AncestorType=ListView}}"
Content="Add Task List" Width="150" HorizontalAlignment="Right" />