【问题标题】:WPF Centering Elements On Canvas Via CodeWPF 通过代码在画布上居中元素
【发布时间】:2011-01-03 20:19:32
【问题描述】:

我找到了这个资源Centering On Canvas。但问题是我不能通过 C# 使用相同的东西,因为画布 left 和 top 值返回零并抛出异常。我并不总是会通过 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>

【问题讨论】:

  • 请发布有意义的 xaml,其中包含所有引用的元素和资源,或者更好地只是剥离您想要实现的目标的示例。
  • 我会第二个斯坦尼斯拉夫。什么试图集中在哪里?
  • 在这种情况下,我试图将一个矩形居中(实际上是任何对象)。
  • 我真的被困住了。我想学习如何在 C# 中编写与上面相同的代码,以使用中值资源使矩形居中。请帮忙....

标签: wpf canvas center


【解决方案1】:

虽然帖子已经很老了,但我只是使用了上面的代码并想分享我的解决方案以防其他人需要它:

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);

}

【讨论】:

    猜你喜欢
    • 2011-01-13
    • 2021-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多