Fif*_*fou 1 listview command mvvm xamarin xamarin.forms
在我的xamarin.forms应用程序中我的ListView上有一个问题,我使用MVVM模式.我希望你能帮助我.这是我的xaml:
<ListView x:Name="MissingVolumeListView"
ItemsSource="{Binding Volumes}"
SelectedItem ="{Binding Id}"
>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid x:Name="Item">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="40"/>
</Grid.ColumnDefinitions>
<Label Text="{Binding Name}" Style="{StaticResource UsualLabelTemplate}"/>
<Button Grid.Column="1" x:Name="DeleteButton" Text ="-" BindingContext="{Binding Source={x:Reference MissingVolumeListView}, Path=BindingContext}" Command="{Binding DeleteVolumeCommand}" CommandParameter="{Binding Source={x:Reference Item}, Path=BindingContext}"/>
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Run Code Online (Sandbox Code Playgroud)
然后我在ViewModel中获取DeleteVolumeCommand:
private ICommand _deleteVolumeCommand;
public ICommand DeleteVolumeCommand
{
get
{
{
if (_deleteVolumeCommand == null)
{
_deleteVolumeCommand = new Command((e) =>
{
var item = (e as Volume);
int index = MissingVolumeListView.Items.IndexOf(item);
});
}
return _deleteVolumeCommand;
}
}
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,当我单击ListView中的Button时,我想要的是获取所选项目.然后,我想让我的ListView获取所选项目的索引,以便从我的ListView中删除它
谢谢您的帮助
Ste*_*rne 11
首先更改删除按钮XAML.
<Button Grid.Column="1"
Text ="-"
Command="{Binding Path=BindingContext.DeleteVolumeCommand, Source={x:Reference MissingVolumeListView}}"
CommandParameter="{Binding .}" />
Run Code Online (Sandbox Code Playgroud)
该命令需要通过listview名称将其绑定上下文更改为视图模型.
但是,命令参数只能传递当前绑定,即列表视图项.
在视图模型中,您无法通过名称引用任何控件.而是使用列表视图将其ItemsSource绑定到的列表 - Volumes.
您可以直接删除该项目.
_deleteVolumeCommand = new Command((e) =>
{
var item = (e as Volume);
Volumes.Remove(item);
});
Run Code Online (Sandbox Code Playgroud)
如果Volumes不是ObservableCollection,请记住也调用notify属性.
| 归档时间: |
|
| 查看次数: |
3183 次 |
| 最近记录: |