无法将列表视图与数据模板绑定

时间:2013-04-03 13:08:12

标签: c# wpf listview binding

我正在使用MVVM,当我右键点击Command时,我想拨打ListView。我做了很多搜索,但我的问题没有解决。

我使用这个XAML代码

<ListView ItemsSource="{Binding LibraryList}"
          x:Name="MediaList" 
          Visibility="{Binding MediaListVisibility}"
          Margin="149,18,-1,0"
          BorderBrush="#FF8BCD7F"
          BorderThickness="0"
          Background="White">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="MouseDoubleClick">
            <i:InvokeCommandAction Command="{Binding ChooseMediaCommand}"
                CommandParameter="{Binding SelectedValue, ElementName=MediaList}"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
    <ListView.View>
        <GridView>
            <GridViewColumn DisplayMemberBinding="{Binding Name}" Header="Name" Width="300" />
            <GridViewColumn DisplayMemberBinding="{Binding Time}" Header="Time" Width="70" />
            <GridViewColumn DisplayMemberBinding="{Binding Artist}" Header="Artist" Width="120" />
            <GridViewColumn DisplayMemberBinding="{Binding Album}" Header="Album" Width="120" />
            <GridViewColumn DisplayMemberBinding="{Binding Year}" Header="Year" Width="80" />
        </GridView>
    </ListView.View> 
    <ListView.ContextMenu>
        <ContextMenu>
            <MenuItem Header="Add to playlist" ItemsSource="{Binding PlaylistsList}">
                <MenuItem.ItemTemplate>
                    <DataTemplate>
                        <MenuItem Header="{Binding Name}"
                                  Command="{Binding AddToPlaylistCommand}"
                                  CommandParameter="{Binding Name}"/>
                    </DataTemplate>
                </MenuItem.ItemTemplate>
            </MenuItem>
            <MenuItem Header="Remove"/>
        </ContextMenu>
    </ListView.ContextMenu>

错误讯息:

  

System.Windows.Data错误:40:BindingExpression路径错误:'对象'''播放列表'(HashCode = 16901761)'上找不到'AddToPlaylistCommand'属性。 BindingExpression:路径= AddToPlaylistCommand; DataItem ='播放列表'(HashCode = 16901761); target元素是'MenuItem'(Name =''); target属性是'Command'(类型'ICommand')

3 个答案:

答案 0 :(得分:3)

使用这样的相对来源(假设您的控件是一个窗口)

Command="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}, Path=AddToPlaylistCommand}"

答案 1 :(得分:2)

Command="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.AddToPlaylistCommand}"

答案 2 :(得分:0)

Command="{Binding Path=DataContext.AddToPlaylistCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}}"