列表框中的 WPF UserControl,将 ICommand 绑定(bind)到 ViewModel

标签 wpf mvvm

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

窗口.xaml:

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

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

用户控件.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?

保罗

最佳答案

<Button Content="Delete" 
        IsEnabled="{Binding CanUserDelete}" 
        Command="{Binding  Path=DataContext.DeleteCurrentUser, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}}">

关于列表框中的 WPF UserControl,将 ICommand 绑定(bind)到 ViewModel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18098494/

相关文章:

c# - 如何在不更改主机文件的情况下阻止对特定站点的访问,直到重新启动?

c# - 启动时将数据传递到新 ViewModel 的最佳方法

wpf - 单击 TextBlock 时如何添加事件?

c# - 如何使用MVVM/ICommand模式在WPF中正确实现BackgroundWorker

wpf - F# 异步和 WPF 进度条

c# - FlexLayout 可绑定(bind)源 -xamarin 表单 - 如何在不绑定(bind)的情况下获取数据

c# - Windows phone 8 数组绑定(bind)似乎没有改变

c# - 这种缓慢的 WPF TextBlock 性能是否符合预期?

C# 在文本框中附加数据

c# - WPF 数据网格 : sort a column programatically the MVVM way?