0

Note: Implementing these view classes as UserControls does solve this issue but UserControls come with their own baggage. Among other issues and annoyances, UserControls cannot be nested. So I'm looking for a solution that does not involve UserControl or require xaml/xaml.cs pairs for each view class.

namespace ViewPropertiesTest
{
    class MyView : Grid
    {
        public MyView()
        {
            this.VerticalAlignment = VerticalAlignment.Bottom;
        }
    }
}

... and when I drop an instance of it onto my main window, the xaml looks like this:

<local:MyView HorizontalAlignment="Left" VerticalAlignment="Top" Margin="269,176,0,0" Width="100" Height="100"/>

When XAML Designer creates and initializes an instance of the MyView class, is there a virtual method that I can override that the Designer calls to allow me to initialize some properties myself?

Clemens
  • 123,504
  • 12
  • 155
  • 268
Greg
  • 143
  • 1
  • 7
  • https://learn.microsoft.com/en-us/dotnet/desktop/wpf/properties/how-to-override-metadata-for-a-dependency-property?view=netdesktop-7.0 – ASh Apr 19 '23 at 20:55
  • @ASh, thanks.the constructor now looks like this: public MyView() { var metadata = new FrameworkPropertyMetadata(VerticalAlignment.Bottom); VerticalAlignmentProperty.OverrideMetadata(typeof(MyView), metadata); } ... but it's not working. I'm assuming that since VerticalAlignmentProperty is defined upstream of me, I just do the override in the constructor – Greg Apr 20 '23 at 01:37
  • just noticed it's a static constructor in the example code. changed is to static, removed everything from MainWindow.xaml so it's just like new, closed MainWindow.xaml, cleaned the solution, rebuilt, opened MainWindow.xaml, dragged in a new instance of MyView... same problem. VerticalAlignment is still set to Top. I feel like i'm getting closer, but still no dice – Greg Apr 20 '23 at 02:54
  • This has nothing to do with the default values of your control's properties. You have to deal with the XAML designer, see the duplicate question. – Clemens Apr 20 '23 at 06:14
  • The most simple approach is to not use the toolbox at all. Just write XAML by hand, it is straightforward and less verbose. – Clemens Apr 20 '23 at 06:26
  • @Clemens, thanks. ChatGPT took about 100 wild stabs at this and failed, and nothing else worked, but you finally got it... using an approach no one had yet mentioned and I've never seen before. Move this to an answer that I can mark as accepted and link to this better-matched example: https://stackoverflow.com/questions/20601321/how-to-set-default-value-to-customcontrol-inherited – Greg Apr 20 '23 at 10:48

0 Answers0