我在 WPF 中动态更新图像的比例时遇到了一些问题。我想要的确切行为是,当我单击按钮时,我想放大(或缩小(UserControl中的图像。
我的 XAML:
<UserControl x:Class="Company.Scaling.ScaleControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<Image x:Name="imageContainer" Stretch="None" Focusable="False" HorizontalAlignment="Left" VerticalAlignment="Top">
<Image.LayoutTransform>
<ScaleTransform x:Name="scaleTransform">
</ScaleTransform>
</Image.LayoutTransform>
</Image>
</Grid>
我目前正在更新属性 ScaleX 和 ScaleY,如下所示:
this.scaleTransform.ScaleX = this.ZoomScale;
this.scaleTransform.ScaleY = this.ZoomScale;
当我在 XAML 的构造函数中更新这些内容时,它可以工作,如下所示:
public ScaleControl()
{
this.InitializeComponent();
this.ZoomScale = 1.5f;
}
但是当我在运行时更新这些属性时(单击按钮后(,它不起作用。
我错过了什么吗?
感谢您的帮助!
编辑:
在克莱门斯说完之后,我补充了一些东西。
XAML 中的绑定:
<Image.LayoutTransform>
<ScaleTransform
ScaleX="{Binding ZoomScale, RelativeSource={RelativeSource AncestorType=UserControl}}"
ScaleY="{Binding ZoomScale, RelativeSource={RelativeSource AncestorType=UserControl}}" />
</Image.LayoutTransform>
依赖属性:
public static readonly DependencyProperty ZoomScaleProperty = DependencyProperty.Register("ZoomScale", typeof(double), typeof(ScaleControl));
和属性:
public double ZoomScale
{
get { return (double)this.GetValue(ZoomScaleProperty); }
set { this.SetValue(ZoomScaleProperty, value); }
}
我对 WPF 很陌生,所以也许我又错过了一些东西,但我无法弄清楚是什么。
设置 ZoomScale 属性不会神奇地更新 ScaleTransform 的 ScaleX 和 ScaleY 属性,只是因为您之前已将 ZoomScale 分配给它们的值。
您必须将 ScaleTransform 属性绑定到 ZoomScale,例如:
<Image ...>
<Image.LayoutTransform>
<ScaleTransform
ScaleX="{Binding ZoomScale,
RelativeSource={RelativeSource AncestorType=UserControl}}"
ScaleY="{Binding ZoomScale,
RelativeSource={RelativeSource AncestorType=UserControl}}" />
</Image.LayoutTransform>
</Image>
有关详细信息,请参阅数据绑定概述。
此外,ZoomScale 属性必须通知值更改。在派生自 DependencyObject 的类中,通常将其声明为依赖项属性,如下所示:
public static readonly DependencyProperty ZoomScaleProperty = DependencyProperty.Register(
"ZoomScale", typeof(double), typeof(ScaleControl));
public double ZoomScale
{
get { return (double)GetValue(ZoomScaleProperty); }
set { SetValue(ZoomScaleProperty, value); }
}
所以,我想我在以下方面添加了正确的东西:
public static readonly DependencyProperty ScalingProperty = DependencyProperty.Register("ZoomScale", typeof(float), typeof(UserControl));
和
public float ZoomScale { get { return (float)GetValue(ScalingProperty); } set { SetValue(ScalingProperty, value); } }
对于依赖项属性。我还添加了:
ScaleX="{Binding ZoomScale, RelativeSource={RelativeSource AncestorType=UserControl}}"
在我的 XAML 中,但似乎没有任何扩展。.