Как конвертировать ImageSource в bool
Я имею Image
а также Button SaveToDisk
, Итак, когда изображение не загружено (ImageSource равен нулю) - мне нужно заблокировать SaveToDisk
кнопка. И наоборот.
Итак, я решил использовать конвертер. Но это не работает для меня:
public class SourceToEnableConverter:IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if ((ImageSource)value == null) return false;
return true;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return Binding.DoNothing;
}
}
Xaml:
<UserControl.Resources>
<converters:SourceToEnableConverter x:Key="SourceToEnableConverter"/>
</UserControl.Resources>
И WPF XAML изображение:
<Image Name="imIcon" Grid.Row="1" Grid.Column="2"
HorizontalAlignment="Left" VerticalAlignment="Center" Margin="8,0,0,8"
>
<Image.Source>
<Binding Path="ObjectViewModel.Image" >
<!--<Binding.TargetNullValue>
<Image Source="Empty.png"></Image>
</Binding.TargetNullValue>-->
</Binding>
</Image.Source>
</Image>
Кнопка:
<Button Name="btnSaveIcon" Click="btnSaveIcon_Click"
Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="6" Margin="8,0,0,8"
HorizontalAlignment="Left" VerticalAlignment="Center"
Content="SaveAs"}"
Height="44"
IsEnabled="{Binding ElementName=imIcon,Path=Source,Converter={StaticResource SourceToEnableConverter}}"
/>
И ошибка вывода:
System.Windows.Data Error: 23 : Cannot convert '<null>' from type '<null>' to type 'System.Windows.Media.ImageSource' for 'ru-RU' culture with default conversions; consider using Converter property of Binding. NotSupportedException:'System.NotSupportedException
Вы можете мне помочь? Может быть, я должен использовать что-то еще? Или я использую IValueConverter
неправильно? Спасибо!
2 ответа
Похоже, что null не является допустимым значением для ImageSource. Попробуйте изменить
if ((ImageSource)value == null) return false;
в
if (value == null) return false;
Я бы использовал Command
вместо. Использовать CanExecute
метод, чтобы определить, включена ли кнопка, например так:
XAML
<Window x:Class="ImageDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:ImageDemo"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<RoutedCommand x:Key="LoadImage"/>
<RoutedCommand x:Key="UnloadImage"/>
</Window.Resources>
<Window.CommandBindings>
<CommandBinding Command="{StaticResource LoadImage}" CanExecute="LoadImage_CanExecute" Executed="LoadImage_Executed"/>
<CommandBinding Command="{StaticResource UnloadImage}" CanExecute="UnloadImage_CanExecute" Executed="UnloadImage_Executed"/>
</Window.CommandBindings>
<DockPanel Margin="5">
<Image x:Name="imgPlaceholder" Height="100" Width="100" DockPanel.Dock="Top"/>
<StackPanel Orientation="Horizontal" Margin="5" HorizontalAlignment="Center" VerticalAlignment="Top">
<Button Content="Load Image" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="10" Command="{StaticResource LoadImage}"/>
<Button Content="Unload Image" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="10" Command="{StaticResource UnloadImage}"/>
</StackPanel>
</DockPanel>
</Window>
Код позади
public partial class MainWindow : Window
{
public BitmapImage bitmap;
public MainWindow()
{
InitializeComponent();
bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.UriSource = new Uri("C:\\Temp\\the_ugly_baby.jpg", UriKind.Absolute);
bitmap.EndInit();
imgPlaceholder.Source = null;
}
private void LoadImage_Executed(object sender, ExecutedRoutedEventArgs e)
{
imgPlaceholder.Source = bitmap;
}
private void LoadImage_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = imgPlaceholder.Source == null ? true : false;
}
private void UnloadImage_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = imgPlaceholder.Source != null ? true : false;
}
private void UnloadImage_Executed(object sender, ExecutedRoutedEventArgs e)
{
imgPlaceholder.Source = null;
}
}
Если CanExecute
является true
тогда ваша кнопка будет включена. Отличная особенность Команд состоит в том, что вы можете повторно использовать их в меню и практически любом элементе управления, в то время как событие Click кнопки действует только для кнопок.
Я бы использовал DataContext
обычно, но чтобы показать использование команд, я думаю, что это будет хорошо.