【问题标题】:WPF UserControl in Listbox, Binding ICommand to ViewModel列表框中的 WPF UserControl,将 ICommand 绑定到 ViewModel
【发布时间】:2013-08-07 18:13:02
【问题描述】:

我已经构建了一个带有一些字段的用户控件和一个删除按钮。 我想在列表框的 DataTemplate 中使用这个用户控件。

Window.xaml:

<ListBox ItemsSource="{Binding Users}">
   <ListBox.ItemTemplate>
     <DataTemplate>
       <WrapPanel>
          <my:User x:Name="user1" />
       </WrapPanel>
     </DataTemplate>
   </ListBox.ItemTemplate>
</ListBox>

在包含列表框的窗口的 ViewModel 中,我为用户控件的 DeleteButton 创建了一个 ICommand。

UserControl.xaml:

<UserControl x:Name="ucUsers" .....>      
    <TextBlock Text="{Binding LastSeen}"  Width="140"/>
    <Button Content="Delete" 
            IsEnabled="{Binding CanUserDelete}" 
            Command="{Binding ElementName=ucUsers, Path=DataContext.DeleteCurrentUser}">
    </Button>

为什么我无法访问 ViewModel 的 DeleteCurrentUser?

保罗

【问题讨论】:

  • 如果你在 UserControl 中有你的 del 按钮,为什么你需要命令。只需使用 del 的按钮单击事件。你想在 del click 上做什么?
  • 试试Command="{Binding DataContext.DeleteCurrentUser, RelativeSource={RelativeSource AncestorType=ListBox}}"

标签: wpf mvvm


【解决方案1】:
<Button Content="Delete" 
        IsEnabled="{Binding CanUserDelete}" 
        Command="{Binding  Path=DataContext.DeleteCurrentUser, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}}">

【讨论】:

  • 只是一个小细节,必须删除“ElementName=ucUsers”,
  • 是的,它不应该在那里。我刚刚复制并粘贴了您的代码并对其进行了编辑。谢谢
猜你喜欢
  • 2015-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-29
  • 1970-01-01
  • 2011-05-09
  • 2017-07-25
  • 2013-08-05
相关资源
最近更新 更多