我正在学习来自WinForm UWP背景的Blazor。我有一个游戏列表:
public class Game
{
public string ID { get; set; }
public string Text { get; set; }
public override string ToString()
{
return Text;
}
}
List<Game> Games = new List<Game> {
new Game() { ID= "Game1", Text= "American Football"},
new Game() { ID= "Game2", Text= "Badminton" },
new Game() { ID= "Game3", Text= "Basketball" },
new Game() { ID= "Game4", Text= "Cricket"},
new Game() { ID= "Game5", Text= "Football" },
new Game() { ID= "Game6", Text= "Golf" },
new Game() { ID= "Game7", Text= "Hockey" },
new Game() { ID= "Game8", Text= "Rugby" },
new Game() { ID= "Game9", Text= "Snooker" },
new Game() { ID= "Game10", Text= "Tennis" },
}; 我想拖放以重新排序我的列表。这是我的元素。
<ul ondragover="event.preventDefault();" style="margin:20px">
@foreach (var item in Games)
{
<li draggable="true" style="list-style-type:none; height:30px" @key="item" tabindex="1"
@onclick="@(()=> ClickItem(item))" @ondrop="@(()=> Drop(item))">
<span>@item.Text</span>
</li>
}
我使用@onclick在列表中选择一个项目:
Game currentGame;
int currentIndex;
void ClickItem(Game item)
{
currentIndex = Games.FindIndex(a => a.Text == item.Text);
currentGame = item;
}
我通过以下方式处理ondrop:
void Drop(Game item)
{
var newIndex = Games.FindIndex(a => a.Text == item.Text);
Games.Insert(newIndex, currentGame);
Games.RemoveAt(currentIndex);
StateHasChanged();
}
Drop方法没有任何反应,列表不会改变,应用程序会中断但不会引发错误并且导航会停止。所有事件都在触发。找不到任何可以帮助您的SO示例。
我设法在BlazorFiddle中为您创建了一个工作示例:
https://blazorfiddle.com/s/8jurefka
根据Henk的建议,我用处理事件ClickItem
的StartDrag
方法替换了您@ondrag
。如果使用@onclick
,则必须先单击一个项目,然后才能拖动它。使用@ondrag
事件可以避免这种情况。我认为在某些情况下这可能是造成问题的原因。
我还添加了一些调试助手,以便可以看到发生了什么。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句