以某种方式可以在ViewBox中设置内容的最大比例吗?如果我有这样的代码,我想确保文本的缩放率不超过200%
<Grid>
<Viewbox>
<TextBox Text="Hello world" />
</Viewbox>
</Grid>
答案 0 :(得分:3)
对于未来的读者,我根据user2250152使用附加属性的答案编写了一个更优雅的方法:
public static class ViewboxExtensions
{
public static readonly DependencyProperty MaxZoomFactorProperty =
DependencyProperty.Register("MaxZoomFactor", typeof(double), typeof(ViewboxExtensions), new PropertyMetadata(1.0, OnMaxZoomFactorChanged));
private static void OnMaxZoomFactorChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var viewbox = d as Viewbox;
if (viewbox == null)
return;
viewbox.Loaded += OnLoaded;
}
private static void OnLoaded(object sender, RoutedEventArgs e)
{
var viewbox = sender as Viewbox;
var child = viewbox?.Child as FrameworkElement;
if (child == null)
return;
child.SizeChanged += (o, args) => CalculateMaxSize(viewbox);
CalculateMaxSize(viewbox);
}
private static void CalculateMaxSize(Viewbox viewbox)
{
var child = viewbox.Child as FrameworkElement;
if (child == null)
return;
viewbox.MaxWidth = child.ActualWidth * GetMaxZoomFactor(viewbox);
viewbox.MaxHeight = child.ActualHeight * GetMaxZoomFactor(viewbox);
}
public static void SetMaxZoomFactor(DependencyObject d, double value)
{
d.SetValue(MaxZoomFactorProperty, value);
}
public static double GetMaxZoomFactor(DependencyObject d)
{
return (double)d.GetValue(MaxZoomFactorProperty);
}
}
附加属性可以添加到这样的视图框中:
<Viewbox extensions:ViewboxExtensions.MaxZoomFactor="2.0">...</Viewbox>
答案 1 :(得分:2)
您需要在MaxWidth
上设置MaxHeight
和ViewBox
:
<Grid>
<Viewbox x:Name="MyViewBox">
<TextBox x:Name="MyTextBox" Text="Hello world" />
</Viewbox>
</Grid>
并在代码背后:
MyViewBox.MaxWidth = MyTextBox.ActualWidth * 2d;
MyViewBox.MaxHeight = MyTextBox.ActualHeight * 2d;
或者更好的转换器解决方案:
public class ViewBoxMaxWidthOrHeightConverter : IValueConverter
{
public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
double textBoxWidthOrHeight = (double) value;
return textBoxWidthOrHeight*2d;
}
public object ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new System.NotImplementedException();
}
}
和XAML:
<local:ViewBoxMaxWidthOrHeightConverter x:Key="ViewBoxMaxWidthOrHeightConverter"/>
<Grid>
<Viewbox x:Name="MyViewBox"
MaxWidth="{Binding ElementName=MyTextBox, Path=ActualWidth, Converter={StaticResource ViewBoxMaxWidthOrHeightConverter}, Mode=OneWay}"
MaxHeight="{Binding ElementName=MyTextBox, Path=ActualHeight, Converter={StaticResource ViewBoxMaxWidthOrHeightConverter}, Mode=OneWay}">
<TextBox x:Name="MyTextBox" Text="Hello world" />
</Viewbox>
</Grid>