【问题标题】:In a WPF Program, I want to change the Stroke Color on all the "Lines" on a "Canvas"在 WPF 程序中,我想更改“画布”上所有“线条”的描边颜色
【发布时间】:2014-03-14 20:28:57
【问题描述】:

我在画布上有一堆线条。 我想遍历线条并将它们的笔触颜色变为黑色。

foreach 循环中的代码行无法编译。

foreach (FrameworkElement Framework_Element in My_Canvas.Children)
{
    //the following line of code won't compile.
    (Line)Framework_Element.Stroke = new SolidColorBrush(Colors.Black);
}

【问题讨论】:

  • Stroke 的底层类型是什么,SolidColorBrush 及其父级是什么类型?看看这个,你应该会得到一些关于如何自己回答问题的线索。
  • @ChrisBallard 我想我毁了你的教学时间。 :>
  • 在典型的 WPF 应用程序中,您不会这样做。相反,您可以定义一个 SolidColorBrush 资源并将所有线条的笔触设置为该资源。稍后,您将只更改 SolidColorBrush 资源的颜色。或者,您可以将 Stroke 属性绑定到应用程序视图模型中的 Brush 属性。

标签: c# wpf canvas


【解决方案1】:

您缺少一对括号。

foreach (FrameworkElement Framework_Element in My_Canvas.Children)
  {
    // tries to find .Stroke on the FrameworkElement class
    // (Line)Framework_Element.Stroke

    // correct way
    ((Line)Framework_Element).Stroke = new SolidColorBrush(Colors.Black);

    // or

    var currentLine = (Line)Framework_Element;
    currentLine.Stroke = new SolidColorBrush(Colors.Black);
  }

【讨论】:

  • 我总是被这些括号搞砸了。该代码现在可以正常使用 ((Line)Framework_Element).Stroke = new SolidColorBrush(Colors.Black);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-02-04
  • 2021-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-17
  • 1970-01-01
相关资源
最近更新 更多