I have a MenuItem, which should be enabled only if there is something selected in ListBox. I wrote a converter from object to bool, which returns false, if that object == null, and true otherwise. I bound it to ListBox.SelectedItem with my converter, but it doesn't work. Placing a breakpoint in the converter shows, that it never runs. The MenuItem appears always enabled no matter what.
Here is xaml code of the ListBox and of MenuItem
<ListBox Name="TestsListBox"
HorizontalAlignment="Left" Height="93" VerticalAlignment="Top" Width="128"
Margin="0,5,-1.723,0" ItemsSource="{Binding Path=Tests, Mode=OneWay}">
<ListBox.ContextMenu>
<ContextMenu>
<MenuItem Header="Remove" Click="removeTest"
IsEnabled="{Binding ElementName=TestsListBox, Mode=OneWay,
Path=SelectedItem, Converter={StaticResource ObjectToBool}}"/>
</ContextMenu>
</ListBox.ContextMenu>
</ListBox>
Here I show how converter is declared as window's resource
<Window x:Class="WpfApplication.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:System="clr-namespace:System;assembly=mscorlib"
xmlns:ClassesLib="clr-namespace:Laba1;assembly=ClassesLib"
xmlns:local="clr-namespace:WpfApplication"
Title="MainWindow" Height="450" Width="525">
<Window.Resources>
<local:ObjectToBoolConverter x:Key="ObjectToBool"/>
</Window.Resources>
And here is the converter class
namespace WpfApplication
{
class ObjectToBoolConverter: IValueConverter
{
// Converts value to boolean. If value is null, returns false.
// Otherwise returns true
public object Convert(object value, Type targetType,
object parameter, System.Globalization.CultureInfo culture)
{
if (null == value)
{
return false;
}
return true;
}
public object ConvertBack(object value, Type targetType,
object parameter, System.Globalization.CultureInfo culture)
{
throw new NotSupportedException("This is oneway converter, so ConvertBack is not supported");
}
}
}