我有一個Image
內Canvas
:中心圖像內畫布
<Canvas>
<Image HorizontalAlignment="Center" VerticalAlignment="Center" />
</Canvas>
我想要顯示的Image
總是(甚至之後可能的調整大小)在我Canvas
的中心,但以這種方式圖像被繪製在左上角。我能怎麼做?
我有一個Image
內Canvas
:中心圖像內畫布
<Canvas>
<Image HorizontalAlignment="Center" VerticalAlignment="Center" />
</Canvas>
我想要顯示的Image
總是(甚至之後可能的調整大小)在我Canvas
的中心,但以這種方式圖像被繪製在左上角。我能怎麼做?
如果您更改圖像和畫布的大小,這個問題最酷的事情是它會起作用。 轉換代碼:
internal sealed class CenterConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
double canvasWidth = System.Convert.ToDouble(values[0]);
double canvasHeight = System.Convert.ToDouble(values[1]);
double controlWidth = System.Convert.ToDouble(values[2]);
double controlHeight = System.Convert.ToDouble(values[3]);
switch ((string)parameter)
{
case "top":
return (canvasHeight - controlHeight)/2;
case "bottom":
return (canvasHeight + controlHeight)/2;
case "left":
return (canvasWidth - controlWidth)/2;
case "right":
return (canvasWidth + controlWidth)/2;
default:
return 0;
}
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
XAML,在資源的地方:
<local:CenterConverter x:Key="CenterConverter" />
XAML:
<Canvas x:Name="superCoolCanvas">
<Image x:Name="superCoolImage" >
<Canvas.Top>
<MultiBinding Converter="{StaticResource CenterConverter}" ConverterParameter="top">
<Binding ElementName="superCoolCanvas" Path="ActualWidth" />
<Binding ElementName="superCoolCanvas" Path="ActualHeight" />
<Binding ElementName="superCoolImage" Path="ActualWidth" />
<Binding ElementName="superCoolImage" Path="ActualHeight" />
</MultiBinding>
</Canvas.Top>
<Canvas.Left>
<MultiBinding Converter="{StaticResource CenterConverter}" ConverterParameter="left">
<Binding ElementName="superCoolCanvas" Path="ActualWidth" />
<Binding ElementName="superCoolCanvas" Path="ActualHeight" />
<Binding ElementName="superCoolImage" Path="ActualWidth" />
<Binding ElementName="superCoolImage" Path="ActualHeight" />
</MultiBinding>
</Canvas.Left>
</Image>
</Canvas>
很好的答案! – gmetax
帆布打算使用絕對座標。您可以使用dwrd提供的解決方案,也可以將Canvas和Image放入網格中,然後將圖像置於該網格中。
我認爲它可以解決使用多個綁定與響應轉換器 – dvvrd
可能重複http://stackoverflow.com/questions/2208992/how-to-center-an-element-in-wpf-canvas –
@dvvrd告訴我如何 – Nick