我找到了这个资源Centering On Canvas。但问题是我不能通过C#使用相同的东西,因为画布左边和顶部的值返回零并抛出异常。我不会总是通过xaml将元素放在画布上,所以我如何使用C#来实现它。请帮忙。
<Canvas.Left>
<MultiBinding Converter="{StaticResource MidValue}"
ConverterParameter="1">
<Binding ElementName="cnvMain2"
Path="ActualWidth" />
<Binding ElementName="tbSize2"
Path="ActualWidth" />
</MultiBinding>
</Canvas.Left>
<Canvas.Top>
<MultiBinding Converter="{StaticResource MidValue}"
ConverterParameter="7">
<Binding ElementName="cnvMain2"
Path="ActualHeight" />
<Binding ElementName="tbSize2"
Path="ActualHeight" />
</MultiBinding>
</Canvas.Top>
答案 0 :(得分:0)
虽然帖子很老,但我刚刚使用了上面的代码,想要分享我的解决方案以防其他人需要它:
public MainWindow()
{
InitializeComponent();
this.SizeChanged += new SizeChangedEventHandler(MainWindow_SizeChanged);
}
void MainWindow_SizeChanged(object sender, SizeChangedEventArgs e)
{
var midValueConverter = new MidValueConverter();
double left = (double)midValueConverter.Convert(new object[] { cnvMain2.ActualWidth, tbSize2.ActualWidth }, typeof(double), null, Thread.CurrentThread.CurrentCulture);
Canvas.SetLeft(tbSize2, left);
double top = (double)midValueConverter.Convert(new object[] { cnvMain2.ActualHeight, tbSize2.ActualHeight }, typeof(double), null, Thread.CurrentThread.CurrentCulture);
Canvas.SetTop(tbSize2, top);
}