到ListView SelectedItem的WPF绑定不起作用
本文关键字:绑定 不起作用 WPF ListView SelectedItem | 更新日期: 2023-09-27 18:04:44
我正在使用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始终可见,并且从不具有图标。有人能告诉我我在俯瞰什么吗?
更新:在.NET3.5中,绑定MenuItem的Icon属性似乎存在一些实际问题,如图所示。我使用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;
}
}
}
编辑:再看一遍,这实际上可能是描述的问题的一个例子
下面的原始答案,但可能不起作用
如果没有看到转换器,我无法评论为什么它可能不起作用,但你可以尝试用一种风格来实现同样的效果:
<ContextMenu.Style>
<Style>
<Style.Triggers>
<DataTrigger Binding="{Binding SelectedItem, ElementName=LogEventListView} Value="{x:Null}">
<Setter Property="Visibility" Value="Collapsed"/>
</DataTrigger>
</Style.Triggers>
</Style>
</ContextMenu.Style>
<Image MaxHeight="16" MaxWidth="16"
Source="{Binding ElementName=LogEventListView,
Path=SelectedItem.Category,
Converter={StaticResource LogEventCategoryConverter}, ConverterParameter='Small'}"/>
我似乎找不到SelectedItem?的名为Category的附加属性??