用列表竞标上下文菜单菜单项可见性

时间:2018-07-11 09:18:14

标签: c# .net wpf listbox contextmenu

我有一个附加到列表框的ContextMenu,后者提供两个选项:创建和删除元素。如果ListBox数据为空,我只想隐藏“ Delete”元素。

我尝试将属性“ Visibility”与视图代码中的变量绑定,将其设置为“ Collapsed”或“ Visible”,但这没有用。

XAML:

<ListBox ItemsSource="{Binding ElementList}"
         SelectedItem="{Binding SelectedElement}"
         SelectionChanged="ListBoxProjects_SelectionChanged">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Grid>
                <TextBlock Text="{Binding Name}" />
            </Grid>
        </DataTemplate>
    </ListBox.ItemTemplate>
    <ListBox.ContextMenu>
        <ContextMenu>
            <MenuItem Name="Add" Click="Add_Click" Header="Add element" />
            <MenuItem Name="Delete" Click="Delete_Click" 
                      HeaderStringFormat="Delete element {0}" 
                      Header="{Binding SelectedElement.Name}" 
                      Visibility="{Binding ElementContextMenuVisibility}" />
        </ContextMenu>
    </ListBox.ContextMenu>
</ListBox>

CS:

public partial class View : UserControl
{
    private ViewModel _viewModel = ViewModel.Instance;

    private Visibility _elementContextMenuVisibility { get; set; }
    public Visibility ElementContextMenuVisibility
    {
        get { return _elementContextMenuVisibility; }
        set { _elementContextMenuVisibility = value; }
    }

    public View()
    {
        InitializeComponent();
    }

    private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (_viewModel.ElementList != null && _viewModel.ElementList.Count > 0)
            ElementContextMenuVisibility = Visibility.Visible;
        else
            ElementContextMenuVisibility = Visibility.Collapsed;
    }
}

谢谢

1 个答案:

答案 0 :(得分:1)

您可以使用RelativeSource绑定来实现此目的,而无需使用xaml.cs代码。

XAML

<ListBox ItemsSource="{Binding ElementList}"
         SelectedItem="{Binding SelectedElement}">
    <ListBox.Resources>
        <BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>
    </ListBox.Resources>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Grid>
                <TextBlock Text="{Binding Name}" />
            </Grid>
        </DataTemplate>
    </ListBox.ItemTemplate>
    <ListBox.ContextMenu>
        <ContextMenu>
            <MenuItem Name="Add" Click="Add_Click" Header="Add element" />
            <MenuItem Name="Delete" Click="Delete_Click" 
                      HeaderStringFormat="Delete element {0}" 
                      Header="{Binding SelectedElement.Name}" 
                      Visibility="{Binding PlacementTarget.HasItems, RelativeSource={RelativeSource AncestorType=ContextMenu}, Converter={StaticResource BooleanToVisibilityConverter}}" />
        </ContextMenu>
    </ListBox.ContextMenu>
</ListBox>