使用用户控件的列表视图中的委派命令
本文关键字:委派 命令 视图 列表 用户 控件 | 更新日期: 2023-09-27 18:35:01
有什么方法可以在我的ListView
内使用我的DelegateCommand
UserControl
:
用户控件:
<UserControl
x:Class="App13.UserControls.ItemTemplateControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App13"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
d:DataContext="{d:DesignInstance Type=local:MainViewModel, IsDesignTimeCreatable=True}"
mc:Ignorable="d">
<Grid>
<Button Content="Click" Command="{Binding OpenCommand"/>
</Grid>
</UserControl>
我的MainViewModel
没有错误.绑定中存在错误。我可以使用以下代码轻松地在 xaml 中使用MainPage
OpenCommand
:
d:DataContext="{d:DesignInstance Type=local:MainViewModel, IsDesignTimeCreatable=True}"
<Button Content="Click" Command="{Binding OpenCommand"/>
如何将OpenCommnad
绑定到我的用户控件?对不起我的英语,提前感谢!
这是我的列表视图:
<ListView x:Name="peopleListBox">
<ListView.ItemTemplate>
<DataTemplate>
<Grid>
<UserControls:ItemTemplateControl/>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
在构建您的用户控件时,请执行
this.DataContext = new MainViewModel();
d:DataContext
只是在运行时不应用的设计时数据上下文设置。
顾
名思义,DesignInstance
用于设计时而不是运行时。
在 MVVM 中,有两种设置ViewModel
的方法。
ViewFirst 或 ViewModelFirst - 取决于您是自上而下还是自下而上构建应用程序。
对于视图优先 您可以从 xaml 设置DataContext
:
<UserControl
x:Class="App13.UserControls.ItemTemplateControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App13"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<UserControl.DataContext>
<local:MainViewModel/>
</UserControl.DataContext>
<!-- Rest of your implementation ... -->
</UserControl>
对于 ViewModelFirst,请将其设置在代码隐藏中(通常从 View 的构造函数完成(
this.DataContext = new MainViewModel();
如果要将 viewModel 中的属性绑定到ListBox
中的项,请按如下方式将按钮绑定到UserControl
内:
<Button Content="Click"
Command="{Binding DataContext.OpenCommand,
RelativeSource={RelativeSource AncestorType={x:Type ListView}}}"
/>
希望这有帮助