【发布时间】:2018-01-17 10:15:53
【问题描述】:
在 winforms 中有 2 个模板:UserControl 允许制作复合控件(现有控件组)以重用它并使用它标准化操作,CustomControl 是一个完全自定义的控件(通常手动呈现,执行方式与标准不同控件等),允许覆盖并提供对protected事物的访问。
在 wpf 中我只找到了UserControl 模板(使用 VS 的快速版)。
要创建自定义MyControl,我正在执行以下操作:
- 创建普通类,基于
Control/ContentControl; - 使用包含控件模板的
Style创建资源字典(可以只有ControlTemplate,样式更好,因为可以包含其他属性设置器)
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:MySolution">
<Style x:Key="MyControl" TargetType="local:MyControl">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:MyControl">
<Grid x:Name="PART_Grid">
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
- 像这样绑定它们
public class MyControl : Control
{
public MyControl()
{
var dictionary = new ResourceDictionary();
dictionary.Source = new Uri("/MySolution;component/MyControl.xaml", UriKind.Relative);
Style = dictionary["MyControl"] as Style;
Loaded += MyControl_Loaded;
}
}
- 在模板中定义 lazy 部分访问器
private Grid _partGrid;
private Grid PartGrid
{
get
{
if (_partGrid == null)
_partGrid = (Grid)Template.FindName("PART_Grid", this);
return _partGrid;
}
}
它有效,但我不确定它是否是最佳方式:
-
.cs和.xaml是单独的文件(不是一个 entity,如 wpfUserControl); - 在移动
xaml(例如,在Controls文件夹内)时,必须调整构造函数代码; - parts 访问器在构造函数中不可用(模板尚未加载)。
我的问题:有没有更好的方法来使用模板进行自定义控件?更舒适、自动化、使用自动部件访问器等。
这是我的 wpf 模板
【问题讨论】:
-
有自定义控件模板。也是控制库的模板。不知道 Express,但有点期待它会在那里。
-
@JohanLarsson,查看编辑,我在屏幕截图上看到here 有
Templated Control,但我没有。也没有此类名称的在线模板。我的问题是否变成“如何获得快速版的模板控制”?它是否解决了我列出的问题?还有,你说“控制库”,我只有“类库”(作为一个新项目)有关系吗? -
@Sinatr 它可能确实与快递有关。我也曾经在 express 中测试过东西,它缺少一些非常重要的模板。这里也可能是这种情况。
标签: c# wpf custom-controls