[英]How to make custom control in WPF
在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;
}
}
private Grid _partGrid;
private Grid PartGrid
{
get
{
if (_partGrid == null)
_partGrid = (Grid)Template.FindName("PART_Grid", this);
return _partGrid;
}
}
它有效,但是我不確定它是否是最佳方法:
.cs
和.xaml
是單獨的文件(不是wpf UserControl
一個實體 ); xaml
(例如,在Controls
文件夾內),必須調整構造函數代碼; 我的問題:有沒有更好的方法可以通過模板進行自定義控件? 更舒適,更自動,帶有自動零件配件等
這是我的WPF模板
最好使用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;
}
請看一下這篇文章,以查看包含該實現細節的示例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.