WPF:通过编程定义控制模板 [英] WPF : Definition Control Template by programmatically

查看:63
本文介绍了WPF:通过编程定义控制模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以使用WPF自定义控件来覆盖某些控件的外观,例如图标按钮。

 公共类MyButton:按钮{

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

但我认为方式有一些问题。当我分发自定义控件 MyButton时,这会引起一些问题。因为MyButton依赖于外部资源,所以WPF样式为MyButton。因此,我需要分发两个文件:MyButton.cs和MyButton.WPF。



那么,如何通过编程方式确定Conotrol模板?



(当然,解决问题的另一种方法是使用WPF用户控制。但我的意思不是那样。)



注意:我找到了一些有关此问题的资源。那是一个内联XAML脚本。但是对我来说,XAML脚本不是选项。因为我正在学习WPF,所以我想自己了解WPF,而不是技巧。

解决方案

不分发代码,而是分发一个包含类和generic.xaml的dll。

这样,另一个设计者/开发人员可以覆盖模板,并且模板保持为安全退后。



编辑



在代码中定义模板是没有乐趣(很多代码,难以调试,难以维护),但是可以做到:

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

EDIT2



另一种方法是在长字符串中指定模板,然后使用XAML分析器加载模板。


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.

解决方案

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.

这篇关于WPF:通过编程定义控制模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆