[英]How do I enable menu items only when an Image's Source property is not null?
What is the best way to only enable menu items when an image's Source
property is not null?当图像的
Source
属性不是 null 时,仅启用菜单项的最佳方法是什么? Here is the XAML:这是 XAML:
<Window.Resources>
<local:IsNullValueConverter x:Key="IsNullValueConverter" />
<local:NotNullValueConverter x:Key="NotNullValueConverter" />
</Window.Resources>
<DockPanel>
<StackPanel DockPanel.Dock="Top" Orientation="Horizontal">
<Button Content="Fill" IsEnabled="{Binding ElementName=TheImage, Path=Source, Converter={StaticResource IsNullValueConverter}}" Click="Fill_Click" />
<Button Content="Erase" IsEnabled="{Binding ElementName=TheImage, Path=Source, Converter={StaticResource NotNullValueConverter}}" Click="Erase_Click" />
</StackPanel>
<Grid DockPanel.Dock="Bottom" Background="White">
<Grid.ContextMenu>
<ContextMenu>
<MenuItem Header="Fill" IsEnabled="{Binding ElementName=TheImage, Path=Source, Converter={StaticResource IsNullValueConverter}}" Click="Fill_Click" />
<MenuItem Header="Erase" IsEnabled="{Binding ElementName=TheImage, Path=Source, Converter={StaticResource NotNullValueConverter}}" Click="Erase_Click" />
</ContextMenu>
</Grid.ContextMenu>
<Image Name="TheImage" />
</Grid>
</DockPanel>
and here is the code:这是代码:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Fill_Click(object sender, RoutedEventArgs e)
{
int width = 1;
int height = 1;
var format = PixelFormats.Gray8;
var pixels = new byte[width * height * (format.BitsPerPixel / 8)];
TheImage.Source = BitmapSource.Create(width, height, 96.0, 96.0, format, null, pixels, width * (format.BitsPerPixel / 8));
}
private void Erase_Click(object sender, RoutedEventArgs e)
{
TheImage.Source = null;
}
}
public class IsNullValueConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value == null;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
public class NotNullValueConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value != null;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
The buttons react exactly how I want: only fill is enabled initially, then once you click it and the image is filled, it is disabled while erase becomes enabled.这些按钮的反应完全符合我的要求:最初仅启用填充,然后单击它并填充图像后,它被禁用,而擦除启用。 However the context menu items are both enabled the entire time, despite their
IsEnabled
properties using the exact same binding as the buttons.然而,上下文菜单项都始终处于启用状态,尽管它们的
IsEnabled
属性使用与按钮完全相同的绑定。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.