【发布时间】:2011-08-05 21:09:27
【问题描述】:
我正在使用 ListView 在我的应用程序中显示日志的内容。我想根据用户当前在 ListView 中选择的条目来更改上下文 MenuItem 的图标和可见性。
这是我填充 ListView 的方式:
// Create the collection view source.
m_CollectionViewSource = new CollectionViewSource();
m_CollectionViewSource.SortDescriptions.Add(new System.ComponentModel.SortDescription("Time", System.ComponentModel.ListSortDirection.Descending));
m_CollectionViewSource.Filter += new FilterEventHandler(LogEventCollectionViewSource_Filter);
// Create the binding.
Binding binding = new Binding();
binding.Source = m_CollectionViewSource;
this.LogEventListView.SetBinding(ListView.ItemsSourceProperty, binding);
m_CollectionViewSource.Source = LogEventManager.Instance.LogEventCollection;
这里是我创建 ListView 控件的地方。
<ListView x:Name="LogEventListView"
Grid.Row="0"
Grid.Column="0"
SelectionMode="Single"
VirtualizingStackPanel.IsVirtualizing="True">
<ListView.ContextMenu>
<ContextMenu Opened="ContextMenu_Opened">
<MenuItem x:Name="ContextMenuViewDetails"
Header="View Details..."
ToolTip="Shows all of the data associated with the log event message."
Visibility="{Binding ElementName=LogEventListView, Path=SelectedItem, Converter={StaticResource NullToVisibilityConverter}}">
<MenuItem.Icon>
<Image MaxHeight="16" MaxWidth="16" Source="{Binding ElementName=LogEventListView, Path=SelectedItem.Category, Converter={StaticResource LogEventCategoryConverter}, ConverterParameter='Small'}" />
</MenuItem.Icon>
</MenuItem>
除了第一个菜单项的绑定之外,一切正常。当未选择某个项目时,我希望折叠第一个菜单项的可见性。我还希望上下文 MenuItem 图像与所选日志事件的图像相匹配。我已经验证了我的两个 IValueConverter 类都正常工作。出于某种原因,第一个 MenuItem 始终是可见的,并且从来没有图标。谁能告诉我我忽略了什么?
更新: 在 .NET 3.5 中绑定到 MenuItem 的 Icon 属性似乎存在一些实际问题,如 here 和 here 所示。由于我使用 IValueConverter 来选择适当的图像,问题变得更加复杂。虽然它不是我更喜欢的解决方案,但现在我决定在 ContextMenu 的打开事件中设置代码隐藏值。
ContextMenu menu = sender as ContextMenu;
if (menu != null)
{
MenuItem item = LogicalTreeHelper.FindLogicalNode(menu, "ContextMenuViewDetails") as MenuItem;
if (item != null)
{
if (this.LogEventListView.SelectedItems.Count <= 0)
item.Visibility = Visibility.Collapsed;
else
item.Visibility = Visibility.Visible;
}
}
}
【问题讨论】:
-
请发布您的转换器。你已经验证了转换器被调用了吗?
-
我已验证转换器工作正常。我在其他地方使用过它们。由于某种原因,他们没有被这个控件调用。
标签: c# wpf xaml data-binding