WPF : Definition Control Template by programmatica

2019-06-04 01:53发布

问题:

We can make WPF Custom Control for overriding some control's look&feel, like icon button.

public class MyButton : Button {

    static MyButton()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(MyButton), new FrameworkPropertyMetadata(typeof(MyButton)));
    }
...
}

But I think that way has a some problem. It causes a some issue when I distribute the Custom Cotrol 'MyButton'. Because MyButton dependent on external resource, the WPF Style MyButton. So I need to distribute two files : MyButton.cs and MyButton.WPF.

So, How can I definite a Conotrol Template by programmatically?

(Of cause, another way to solving the problem is making WPF User Control. but my point is not that.)

Note : I found some resources about this issue. That was a Inline XAML scripting. But to me, the XAML scripting is not option. Because I'm learning on WPF so I want to know WPF thatself, not a trick.

回答1:

You do not distribute the code, you distribute a dll that contains the class and the generic.xaml

That way another designer/developer can 'override' the template and your template stays as a safe fall-back.

EDIT

Defining a Template in code is no fun (a lot of code, hard to debug, hard to maintain) but it can be done:

var template = new ControlTemplate(typeof(MyControl));

EDIT2

Another hack is to specify the template in a long string and use the XAML Parser to load it.