我想在DataTemplate元素中绑定gridview-click。我必须使用DataTemplate元素,因为它是HubSections所必需的。
如果我在DataTemplate元素中绑定此命令,则会收到错误:
“对象引用未设置为对象的实例”
<Frame x:Name="frame">
<Hub VerticalAlignment="Center" HorizontalAlignment="Center" >
<HubSection Width="250" x:Name="section1" IsHeaderInteractive="True" >
<DataTemplate>
<GridView IsItemClickEnabled="True" ItemClick="{x:Bind MainPageVM.click}">
<RelativePanel>
<Image x:Name="image" Source="Assets/1.png" Width="Auto" Height="250" />
<TextBlock x:Name="page1" Text="page1" />
</RelativePanel>
</GridView>
</DataTemplate>
</HubSection>
//....
</Hub>
</Frame>
但是,如果我在DataTemplate元素之外绑定相同的处理程序(例如HubSectionHeaderClick),它可以正常工作。
但我不明白为什么?我有什么选择来解决这个问题?
修改 这里是带有ElementName的XAML:
<Hub VerticalAlignment="Center" HorizontalAlignment="Center" x:Name="ThisIsHub" >
和Binding:
Binding ElementName=ThisIsHub, Path=DataContext.click
得到错误:
无法在“对象”类型的数据上下文中解析属性“click”
答案 0 :(得分:0)
在GridView / ListView上绑定click事件时,我总是遵循本教程(这里是链接:https://marcominerva.wordpress.com/2013/03/07/how-to-bind-the-itemclick-event-to-a-command-and-pass-the-clicked-item-to-it/)
首先,您必须创建一个定义附加属性的类:
public static class ItemClickCommand
{
public static readonly DependencyProperty CommandProperty =
DependencyProperty.RegisterAttached("Command", typeof(ICommand),
typeof(ItemClickCommand), new PropertyMetadata(null, OnCommandPropertyChanged));
public static void SetCommand(DependencyObject d, ICommand value)
{
d.SetValue(CommandProperty, value);
}
public static ICommand GetCommand(DependencyObject d)
{
return (ICommand)d.GetValue(CommandProperty);
}
private static void OnCommandPropertyChanged(DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
var control = d as ListViewBase;
if (control != null)
control.ItemClick += OnItemClick;
}
private static void OnItemClick(object sender, ItemClickEventArgs e)
{
var control = sender as ListViewBase;
var command = GetCommand(control);
if (command != null && command.CanExecute(e.ClickedItem))
command.Execute(e.ClickedItem);
}
}
然后在XAML中以这种方式使用它(它适用于ListView / GridView):
helpers:ItemClickCommand.Command="{Binding Click}
其中helpers
是您在其中定义附加属性
然后在viewmodel中定义命令:
private RelayCommand<MyItem> click;
public RelayCommand<MyItem> Click
{
get
{
if (click== null)
{
click= new RelayCommand<MyItem>(
(item) =>
{
//do something with your item
});
}
return click;
}
}
让我知道它是否有效!
答案 1 :(得分:0)
我认为您的视图模型绑定到hubsection DataContext,因此当您将命令放入HubSectionHeaderClicked事件时它可以正常工作。所以试试这个
使用此绑定
{Binding ElementName=section1,Path="DataContext.clickcommand}
让我知道它是否有效