创建一个值转换器,将复选框的选中状态转换为Stretch.Unfiorm
或Stretch.None
。
public class StretchValueConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return (bool)value ? Stretch.Uniform : Stretch.None;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return value.Equals(Stretch.Uniform);
}
}
然后在您的 XAML 中,您可以执行以下操作:
<Window.Resources>
<local:StretchValueConverter x:Key="StretchValueConverter" />
</Window.Resources>
<CheckBox x:Name="FitToScreen" />
<ScrollViewer VerticalScrollBarVisibility="Auto"
HorizontalScrollBarVisibility="Auto">
<Image Source="{Binding Picture}" Stretch="{Binding ElementName=FitToScreen Converter={StaticResource StretchValueConverter}, Path=Checked"/>
</ScrollViewer>
更新
您还需要设置HorizontalScrollBarVisibility
并VerticalScrollBarVisibilty
强制Disabled
滚动查看器的内容不超过边界。您可以使用另一个转换器或样式来监听 Checkbox.Checked 属性。
<Window x:Class="Overflow.Examples.Wpf.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<CheckBox x:Name="FitToScreen" Grid.Row="0" Content="Fit to screen" />
<ScrollViewer Grid.Row="1">
<Image Source="{Binding Picture}">
<Image.Style>
<Style TargetType="Image">
<Setter Property="Stretch" Value="None" />
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=FitToScreen, Path=IsChecked}" Value="True">
<Setter Property="Stretch" Value="Uniform" />
</DataTrigger>
</Style.Triggers>
</Style>
</Image.Style>
</Image>
<ScrollViewer.Style>
<Style TargetType="ScrollViewer">
<Setter Property="HorizontalScrollBarVisibility" Value="Auto" />
<Setter Property="VerticalScrollBarVisibility" Value="Auto" />
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=FitToScreen, Path=IsChecked}" Value="True">
<Setter Property="HorizontalScrollBarVisibility" Value="Disabled" />
<Setter Property="VerticalScrollBarVisibility" Value="Disabled" />
</DataTrigger>
</Style.Triggers>
</Style>
</ScrollViewer.Style>
</ScrollViewer>
</Grid>
</Window>