There is a ListBox . He has his own ContextMenu . So, how to make it so that when selecting several lines, a certain item in the menu is made available?

I tried through DepedenceProperty :

 public bool IsOneItemSelected { get { return (bool)GetValue(IsOneItemSelectedProperty); } set { SetValue(IsOneItemSelectedProperty, value); } } // Using a DependencyProperty as the backing store for IsMultiSelected. This enables animation, styling, binding, etc... public static readonly DependencyProperty IsOneItemSelectedProperty = DependencyProperty.Register("IsOneItemSelected", typeof(bool), typeof(MainWindow)); /// <summary> /// Включение/выключение пунктов меню, в зависимоти от выбранных файлов /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ListBox_ContextMenuOpening(object sender, ContextMenuEventArgs e) { IsOneItemSelected = ((sender as ListBox).SelectedItems.Count > 1)? false : true; } 

in XAML (desired item - Merge selected files ):

 <ListBox x:Name="listBox" ItemsSource="{Binding Planshets}" ContextMenuOpening="ListBox_ContextMenuOpening" SelectionMode="Extended"> <ListBox.ContextMenu> <ContextMenu> <MenuItem Header="Добавить файлы" Click="btAdd_Planshets"/> <MenuItem Header="Удалить файлы" Click="MenuItem_Click_3"/> <Separator/> <MenuItem Header="Конвертировать ..."/> <MenuItem Header="Объединить выбранные файлы" IsEnabled="{Binding IsOneItemSelected, ElementName=window}" /> <Separator/> <MenuItem Header="Очистить список" Click="miClear_Planshets"/> </ContextMenu> </ListBox.ContextMenu> </ListBox> 
  • And why not install IsOneItemSelected on SelectionChanged? - VladD
  • Yes, it still does not work ... The item is available all the time, even when there is nothing in the list. Although IsOneItemSelected changes its value - MaximK

1 answer 1

Made through converter.

 /// <summary> /// Конвертер для включения доп. функций если выбрано бельше чем один элемент в списке /// </summary> [ValueConversion(typeof(int), typeof(bool))] public class MultiSelectAddon : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { return ((int)value > 1) ? true: false; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } 

Using:

 <Button x:Name="button" Content="Merge" IsEnabled="{Binding SelectedItems.Count, Converter={StaticResource MultiSelectAddon}, ElementName=listBox, Mode=OneWay}" /> 

For digging works, for ContextMenuItem - No.

Here is another option Getting the selected lines

  • Hmm, does it work like that? Is Count DependencyProperty? Hardly. - VladD
  • Count on ... works with button , but not with ContextMenu - MaximK
  • Hm And if in ContextMenu just writing <MenuItem Header="Объединить выбранные файлы" IsEnabled="false" /> , will it work? - VladD
  • just false works - MaximK