Pra*_*nds 11 xaml gridview winrt-xaml windows-store-apps
我正在Visual Studio 2012中创建我的第一个Windows应用商店应用.我有一个gridview控件,我已经启用了重新排序.我有重新排序列表时需要运行的代码.我尝试过Drop事件.它不会开火.我尝试了其他几个拖拽事件,但也没有开火.看起来应该这么简单......谢谢你的时间!
Jer*_*xon 23
GridView除非ItemsSource绑定到ObservableCollection和,并且设置为CanReorderItems,否则不能重新排序.这是不是必须使用,使重新排序的.实际上,a 经常用于分组a,并且在对数据进行分组时不可能进行重新排序.CanDragItemsAllowDroptrueCollectionViewSourcegridviewcollectionviewsourcegridview
无论如何,你的XAML看起来像这样:
<Grid Background="Black">
<Grid.DataContext>
<local:MyModel/>
</Grid.DataContext>
<GridView CanReorderItems="True" CanDragItems="True" AllowDrop="True"
ItemsSource="{Binding Items}">
</GridView>
</Grid>
Run Code Online (Sandbox Code Playgroud)
虽然任何enumerable可结合到ItemsSource的GridView它仅仅是一个ObservableCollection,使重新排序.是的,你可以使用一个实现重新排序的自定义类型,但是为什么ObservableCollection它适合你呢?
您的视图模型可能如下所示:
public class MyModel
{
public MyModel()
{
foreach (var item in Enumerable.Range(1, 50))
Items.Add(item);
Items.CollectionChanged += Items_CollectionChanged;
}
ObservableCollection<int> m_Items = new ObservableCollection<int>();
public ObservableCollection<int> Items { get { return m_Items; } }
object m_ReorderItem;
int m_ReorderIndexFrom;
void Items_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
switch (e.Action)
{
case NotifyCollectionChangedAction.Remove:
m_ReorderItem = e.OldItems[0];
m_ReorderIndexFrom = e.OldStartingIndex;
break;
case NotifyCollectionChangedAction.Add:
if (m_ReorderItem == null)
return;
var _ReorderIndexTo = e.NewStartingIndex;
HandleReorder(m_ReorderItem, m_ReorderIndexFrom, _ReorderIndexTo);
m_ReorderItem = null;
break;
}
}
void HandleReorder(object item, int indexFrom, int indexTo)
{
Debug.WriteLine("Reorder: {0}, From: {1}, To: {2}", item, indexFrom, indexTo);
}
}
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,重新排序event不是真实的.它源自CollectionChanged事件中"删除"操作和"添加"操作的组合.这就是为什么这很棒.如果重新订购只能从GridView当时获得,那么ViewModel将无法处理它.由于基础列表是您检测重新排序的方式,因此ViewModel已启用.
每个案例都略有不同.您可能不关心索引,因此您可以简化代码.您可能不允许在集合中添加或删除,因此您只需要监视"添加"操作.这又取决于你的情况.我上面的示例代码应该得到99%的案例处理.
请记住,GridView不是唯一允许重新排序的控件.任何基于ListViewBase(像ListView)的控件都支持重新排序 - 仍在使用ObservableCollection.但是GridView使用此功能的最常见控件.当然.
参考:http://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.controls.listviewbase.canreorderitems
哦,回答你的问题!
没有任何事件表明重新订购.重新排序是基于基础ObservableCollection CollectionChanged事件中的操作组合的派生操作.合理?
顺便说一句,这里是绑定到a的示例语法CollectionViewSource,如果您选择:
<Grid Background="Black">
<Grid.DataContext>
<local:MyModel/>
</Grid.DataContext>
<Grid.Resources>
<CollectionViewSource x:Name="CVS" Source="{Binding Items}" />
</Grid.Resources>
<GridView CanReorderItems="True" CanDragItems="True" AllowDrop="True"
ItemsSource="{Binding Source={StaticResource CVS}}" >
</GridView>
</Grid>
Run Code Online (Sandbox Code Playgroud)
祝你好运.
| 归档时间: |
|
| 查看次数: |
5939 次 |
| 最近记录: |