c# - SwipeItem XAML 绑定被忽略
问题描述
我无法让任何绑定在 aSwipeItem
内工作RadListView
(类似于标准ListView
)。特别是,我正在尝试绑定到该Command
属性;但是,我尝试绑定到其他属性,例如 ,Text
但无济于事。
<telerikDataControls:RadListView ItemsSource ="{Binding Users, Mode=OneWay}">
<telerikDataControls:RadListView.ItemTemplate>
<DataTemplate>
<SwipeControl>
<SwipeControl.RightItems>
<SwipeItems>
<SwipeItem Text="Delete"
Background="Red"
Foreground="White"
Command="{Binding DeleteCommand}">
<SwipeItem.IconSource>
<SymbolIconSource Symbol="Delete"/>
</SwipeItem.IconSource>
</SwipeItem>
</SwipeItems>
</SwipeControl.RightItems>
<Grid>
<TextBlock Text="{Binding Name"/>
</Grid>
</SwipeControl>
</DataTemplate>
</telerikDataControls:RadListView.ItemTemplate>
</telerikDataControls:RadListView>
Users
在 ViewModel 的构造函数中为 View 设置;它是ObservableCollection
of UserViewModel
,每个都有我要使用的属性(使用 PropertyChanged 事件)。
Name
绑定在模板的更Grid
下方工作,我检查了DataContext
的SwipeControl
,它是UserViewModel
. 在我的测试中,我设置了Event
一个SwipeItem
:
<SwipeItem Text="Delete"
Background="Red"
Foreground="White"
Command="{Binding DeleteCommand}"
Invoked="SwipeItem_Invoked">
并在代码隐藏中处理它:
private void SwipeItem_Invoked(SwipeItem sender, SwipeItemInvokedEventArgs args)
{
UserViewModel userToDelete = (UserViewModel)args.SwipeControl.DataContext;
}
sender.Command
我可以在这里看到null
。
显然,快速的解决方案是使用事件模式;但是,我试图将其保留为 MVVM 并尽可能避免代码隐藏。我以前从未遇到过绑定到属性的问题,所以想象一下我只是在做一些根本错误的事情。
谢谢。
编辑:
public class UserViewModel : MvxNotifyPropertyChanged // MvvmCross
{
public IMvxAsyncCommand DeleteCommand { get; }
private string _name;
public string Name // this property is bound in the Grid but will not bind in the SwipeItem
{
get => _name;
set => SetProperty(ref _name, value);
}
}
解决方案
如果 Invoked 事件正在触发,但您无法使 Command 绑定工作,那么您可以尝试使用 XAML 行为(又名混合行为)将您的命令连接到正在触发的事件。这应该允许您保持代码 MVVM 友好。
首先,安装 Microsoft.Xaml.Behaviors.Uwp.Managed nuget 包,然后将 XAML 更改为以下内容:
<SwipeItem xmlns:interactivity="using:Microsoft.Xaml.Interactivity"
xmlns:core="using:Microsoft.Xaml.Interactions.Core"
Text="Delete"
Background="Red"
Foreground="White">
<interactivity:Interaction.Behaviors>
<core:EventTriggerBehavior EventName="Invoked">
<core:InvokeCommandAction Command="{Binding Path=DeleteCommand}" />
</core:EventTriggerBehavior>
</interactivity:Interaction.Behaviors>
<SwipeItem.IconSource>
<SymbolIconSource Symbol="Delete"/>
</SwipeItem.IconSource>
</SwipeItem>
为了使答案保持简洁,我在 SwipeItem 元素中定义了交互性和核心 xml 命名空间 - 但这些通常会移动到 XAML 中的顶级元素。
推荐阅读
- java - 在封闭范围内定义的局部变量 min 必须是 final 或有效 final
- sql-server - 无法让 where 子句处理包含单引号的文本
- elasticsearch - 使用 StormCrawler(和 Elasticsearch)将字段添加到爬网内容
- node.js - mongoose 5.8 和 mongodb 连接应该怎么做?
- azure - 无法通过 spark HdInsight 中的 anaconda py35 env 进行操作调用
- android - 删除的权限仍列在 Google Play 列表中(早期访问中的应用)
- ios - Swift 5.1 的最低支持 iOS 是多少?
- xml - 使用happymapper时使用命名空间映射深度嵌套的元素
- python - Python Selenium 单击带有类的按钮
- javascript - Javascript 类在 Chrome 上运行良好,但在 Edge 上运行良好。为什么?