切换 GridControl 的选定项的菜单项可见性



我的WPF上有一个GirdControl,它绑定到类型为NoteFrontEnd的对象。NoteFrontEnd中有一个名为NoteType的属性,我想将其用作MenuItem中可见性绑定的源。

用户必须右键单击GridControl中的一个NoteFrontEnd对象,并根据其NoteType属性,使用Header="Process Item"显示或隐藏MenuItem

GridControlMenuItem在xaml中定义为:

<dxg:GridControl Name="GridCtrl"
ItemsSource="{Binding Path=BaseDashboardDataSource}"
SelectedItems="{Binding SelectedItems, Mode=TwoWay}"
AutoGenerateColumns="None">
<dxg:GridControl.Columns>
...
<dxg:GridColumn x:Name="NoteType"  FieldName="NoteType" Header="Type" />
</dxg:GridControl.Columns>
<dxg:GridControl.View>
<dxg:TableView.ContextMenu>
<ContextMenu>
<ContextMenu.ItemsSource>
<CompositeCollection>
...
<!--Menu Item to toggle visibility of-->
<MenuItem Header="Process Item"
Visibility="{Binding ElementName=GridCtrl, Path=SelectedItem, Converter={StaticResource GVItemToVis}}"     
Command="{...}">
</MenuItem>
</CompositeCollection>
</ContextMenu.ItemsSource>
</ContextMenu>
</dxg:TableView.ContextMenu>
</dxg:TableView>
</dxg:GridControl.View>
</dxg:GridControl>

我的ViewModel定义如下:

public class NoteViewModel : DashboardViewModelBase
{
...
public ObservableCollection<NoteFrontEnd> BaseDashboardDataSource { get; private set; }
public ObservableCollection<BrokerNoteFrontEnd> SelectedItems
{
get { return _selectedItems; }
set
{
if (_selectedItems == value) return;
_selectedItems = value;
OnPropertyChanged();
}
}
public NoteViewModel(...) {
...
BaseDashboardDataSource = new ObservableCollection<NoteFrontEnd>();
}
}

NoteFrontEnd为:

public class NoteFrontEnd
{
public string NoteType { get; set; }
}

不过,我得到了以下错误:

Cannot find source for binding with reference 'ElementName=GridCtrl'. BindingExpression:Path=SelectedItems;...

我尝试过其他绑定,如下面的,但得到了相同的错误:

Visibility="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=Grid}, Path=PlacementTarget.SelectedItem, Converter={StaticResource GVItemToVis}}"

我怎样才能使这种绑定生效?

上下文菜单是一个单独的窗口。它与您的网格控件的名称范围不同。

我建议你:

将上下文菜单与每个NoteFrontEnd所在的行相关联,而不是与整个网格相关联。

NoteFrontEnd应该是实现inotifypropertychanged的视图模型。即使您没有要通知的更改。始终绑定到对象实现inpc并避免绑定导致内存泄漏的可能性。

这意味着您可以使用下面的或变体来获取该行的数据上下文:

<ContextMenu DataContext="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource Self}}"

这意味着datacontext指向注释,该注释被模板化到单击的行中。

然后你可以在你的NoteFrontEnd中放一个命令,做任何应该做的事情

您还可以将此菜单项的可见性绑定到一个基于前端并封装任何逻辑的属性

我建议您(相反(考虑使用icommand的canexecute部分,并在用户不应该单击此选项时返回false。这样,条目仍然会出现在上下文菜单中,但会被禁用并变灰。

最新更新