【问题标题】:How to make custom control in WPF如何在 WPF 中制作自定义控件
【发布时间】: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,如 wpf UserControl);
  • 在移动xaml(例如,在Controls 文件夹内)时,必须调整构造函数代码;
  • parts 访问器在构造函数中不可用(模板尚未加载)。

我的问题:有没有更好的方法来使用模板进行自定义控件?更舒适、自动化、使用自动部件访问器等。


这是我的 wpf 模板

【问题讨论】:

  • 有自定义控件模板。也是控制库的模板。不知道 Express,但有点期待它会在那里。
  • @JohanLarsson,查看编辑,我在屏幕截图上看到here 有Templated Control,但我没有。也没有此类名称的在线模板。我的问题是否变成“如何获得快速版的模板控制”?它是否解决了我列出的问题?还有,你说“控制库”,我只有“类库”(作为一个新项目)有关系吗?
  • @Sinatr 它可能确实与快递有关。我也曾经在 express 中测试过东西,它缺少一些非常重要的模板。这里也可能是这种情况。

标签: c# wpf custom-controls


【解决方案1】:

如果你使用 CustomControl VS 模板会更好,不知道为什么你看不到它,可能是因为你使用的是 Express 版本。该模板为您生成一个 Generic.xaml 文件,您可以在其中定义样式/控件模板。此外,您将拥有带有 c# 控件定义的 .cs。

要获取控件的不同部分,推荐的方法是使用 GetTemplateChild 方法并传递 Part_Name,您通常会覆盖 OnApplyTemplate() 方法。

 public override void OnApplyTemplate()
  {
    base.OnApplyTemplate();

    ActionBtn = GetTemplateChild(BtnPartName) as ButtonBase;
    ContentPopup = GetTemplateChild(PopupPartName) as Popup;
  }

查看this post 以查看包含该实施细节的示例。

【讨论】:

    猜你喜欢
    • 2012-10-22
    • 2011-04-15
    • 2018-10-24
    • 2011-08-25
    • 1970-01-01
    • 2017-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多