0

This is absolutely ridiculous! I'm trying to change the color of inkCanvas through code but it doesn't work. I saw a lot of tutorials about that and they don't work for me. Even though they're straightforward. I'm new to WPF but still - this should be a no-brainer.

*Note: I can set the color through XAML but that's a one-time operation and not what I want.

My code:

using System.Windows;
using System.Windows.Controls;
using System.Windows.Ink;
using System.Windows.Media;

namespace WpfApplication1
{
    public partial class MainWindow : Window
    {
        InkCanvas inkCanvas = new InkCanvas();

        public MainWindow()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(SetColor);
        }

        // doesn't work
        private void SetColor(object sender, RoutedEventArgs e)
        {
            inkCanvas.DefaultDrawingAttributes.Color = Colors.Red;
        }
         // doesn't work either
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            inkAttributes.Color = Colors.Blue;
        }
    }
}

Edit: My XAML was:

<Window...
< InkCanvas Name="inkCanvas" /> ....
Bruno
  • 613
  • 1
  • 7
  • 8

1 Answers1

2

In your code sample, you define inkCanvas in the window's code-behind, but don't add it to the window's visual controls.

If you either specify the canvas using XAML:

<Window x:Class="..."
        ...>
    <InkCanvas x:Name="inkCanvas"/>
</Window>

or define it in C# and add it to the window:

InkCanvas inkCanvas = new InkCanvas();

public MainWindow()
{
    InitializeComponent();
    this.Loaded += (sender, args) =>
    {
        this.AddChild(inkCanvas);
    };
}

Then the line inkCanvas.DefaultDrawingAttributes.Color = Colors.Red; shold actually work.

andreask
  • 4,248
  • 1
  • 20
  • 25
  • That's it! In XAML I used the "Name" attribute instead of "x:Name". I didn't even thought about searching for the problem there. It appears the later makes the connection with code-behind. Thank you very much! – Bruno Jan 07 '16 at 14:56
  • Actually, the problem was that I had defined `InkCanvas inkCanvas = new InkCanvas();` in code-behind even though I already had an element with such name. Removing the line fixes this ambiguity(which the compiler does not mark as problematic). – Bruno Jan 07 '16 at 15:08