【发布时间】:2014-03-06 18:26:52
【问题描述】:
我有一个绑定到自定义对象列表的列表框。我可以使用 xaml 中的 ListBox.ItemTemplate 正确显示列表框项目。列表框的自定义对象都是下面列出的相同基类。
public class HomeViewMenuItem : UIElement
{
private Uri _uri;
private IRegionManager _manager;
public HomeViewMenuItem(string text, Uri uri, IRegionManager manager)
{
this.PreviewMouseDown += HomeViewMenuItem_PreviewMouseDown;
this.PreviewKeyDown += HomeViewMenuItem_PreviewKeyDown;
_manager = manager;
Text = text;
_uri = uri;
ClickCommand = new DelegateCommand(this.Click, this.CanClick);
}
void HomeViewMenuItem_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
if (e.Key == System.Windows.Input.Key.Enter)
{
e.Handled = true;
this.ClickCommand.Execute();
}
}
void HomeViewMenuItem_PreviewMouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
e.Handled = true;
this.ClickCommand.Execute();
}
private void Click()
{
_manager.Regions[RegionNames.MainRegion].RequestNavigate(_uri);
}
private bool CanClick()
{
return true;
}
public DelegateCommand ClickCommand { get; set; }
public string Text { get; set; }
}
我遇到的问题是没有调用 HomeViewMenuItem_PreviewKeyDown 方法。我相信这是因为该方法首先在 ListBoxItem 本身上被调用并在那里得到处理。在 ItemContainerGenerator 状态更改为 ContainersGenerated 并在那里添加事件处理程序后,我能够通过 listBox.ItemContainerGenerator.ContainerFromIndex(0) 获取对 ListBoxItem 对象的引用来验证这一点。此事件处理程序正确触发。通常这对于一个小项目来说是一个不错的解决方案,但我计划拥有更多具有相同功能的列表框,并希望有一个更简单/更好的解决方案。有没有办法让我的基类 previewkeydown 方法工作?
我能想到的唯一解决方案是让基类继承自 ListBoxItem 而不是 UIElement,然后让 ListBox 来创建我的项目而不是 ListBoxItems。但如果不创建我自己的 ListBox 实现,我认为这是不可能的。
【问题讨论】: