我在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很陌生,所以也许我又错过了一些东西,但我无法弄清楚是什么。
答案 0 :(得分:2)
设置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>
有关详细信息,请参阅Data Binding Overview。
此外,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); }
}
答案 1 :(得分:0)
所以,我认为我已经添加了正确的内容:
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中但似乎没有任何规模......