我无法让任何绑定(bind)为 SwipeItem
工作在 RadListView
内(类似于标准 ListView
)。特别是,我试图绑定(bind)到 Command
属性(property);但是,我尝试绑定(bind)到其他属性,例如 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
的 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 并尽可能避免代码隐藏。我以前从未遇到过绑定(bind)到属性的问题,所以想象一下我只是在做一些根本错误的事情。
谢谢。
编辑:
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 绑定(bind)工作,那么您可以尝试使用 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 中的顶级元素。
关于c# - SwipeItem XAML 绑定(bind)被忽略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53560468/