我想制作一个汉堡菜单。这是 XAML。
<SplitView Grid.Row="1" HorizontalAlignment="Left">
<SplitView.Content>
<ListView>
<ItemsControl x:Name="NavItemsControl">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel></StackPanel>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"></ColumnDefinition>
<ColumnDefinition Width="*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBlock FontFamily="Segoe MDL2 Assets" Text="{Binding Icon}"></TextBlock>
<TextBlock Text="{Binding Content}" Grid.Column="1"></TextBlock>
</Grid>
</Button>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ListView>
</SplitView.Content>
</SplitView>
这是背后的代码:
public class NavItems : INotifyPropertyChanged
{
string _Icon;
public string Icon
{
set
{
_Icon = value;
OnPropertyChanged("Icon");
}
get
{
return _Icon;
}
}
string _Content;
public string Content
{
set
{
_Content = value;
OnPropertyChanged("Content");
}
get
{
return _Content;
}
}
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
}
设置了 NavItemsControl 的 ItemSource 后,我可以轻松绑定(bind) Icon 或 Content 等属性。唯一的问题是我想绑定(bind) 的 click 事件
按钮,但我不知道如何绑定(bind)它。
我尝试使用delegate绑定(bind)点击事件,但是不起作用并报错。
您能帮我一下吗?
谢谢
最佳答案
在回答您的问题之前,我们首先修复您的 XAML。您正在使用ListView
包裹 ItemsControl
,这是不必要的。实际上,ListView
本身继承自 ItemsControl
基本上是它的一个更强大的版本。在您的情况下, ItemsControl
应该足够了,这样您就可以安全地删除 ListView
包装器。
自从您使用了 Button
在模板中,您可以创建 ClickCommand
(类型为 ICommand
)在 NavItems
中并绑定(bind)Button
的Command
其属性。
<Button Command="{Binding ClickCommand}" />
互联网上有大量资源,您可以在其中找到 ICommand
实现,看看它是如何在 UWP Toolkit 中完成的.
旁注
我个人不喜欢使用 SelectionChanged
因为它是一个数据驱动事件,可以由数据更改触发。这可能是不可预测的并且容易出错。此外,除非您手动重置SelectedIndex
,否则您无法重新选择相同的项目。 。一个按钮Click
(或 ItemClick
中的 ListView
)是一个输入驱动的事件,只能(在大多数情况下)由用户操作调用,这很少会给您带来任何副作用。
关于uwp - 如何绑定(bind)UWP的ItemsControl中的点击事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45543082/