为什么我们实际上需要用户控件?
窗户:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:wpfApplication1="clr-namespace:WpfApplication1">
<wpfApplication1:SaveCloseUserControl />
</Window>
用户控件:
<UserControl x:Class="WpfApplication1.SaveCloseUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<StackPanel Orientation="Horizontal">
<Button Height="30" Content="Save" />
<Button Height="30"
Margin="1"
Content="Cancel" />
</StackPanel>
</UserControl>
后面的代码:
public partial class SaveCloseUserControl : UserControl
{
public SaveCloseUserControl()
{
InitializeComponent();
}
}
我看不出为什么要在用户控件内包装StackPanel(或任何其他控件)的任何原因,如果以下不带用户控件的代码会完全一样。
窗户:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:wpfApplication1="clr-namespace:WpfApplication1">
<wpfApplication1:SaveCloseStackPanel />
</Window>
没有用户控制的堆叠面板:
<StackPanel x:Class="WpfApplication1.SaveCloseUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Orientation="Horizontal">
<Button Height="30" Content="Save" />
<Button Height="30"
Margin="1"
Content="Cancel" />
</StackPanel>
后面的代码:
public partial class SaveCloseUserControl : StackPanel
{
public SaveCloseUserControl()
{
InitializeComponent();
}
}
我到处都在使用UserControls,但是现在,当我考虑它时,除了将项目包装在其中之外,它们什么也没有做。因此,我在10种不同的视图上进行了尝试,无论它是什么,我都可以用其他项(Grid,ComboBox,GroupBox等)替换UserControl,并且它们的工作方式完全相同。因此要清楚一点,如果我有一个用户控件,并且其中第一件事是ComboBox,则删除了UserControl并将ComboBox放在了它的位置。就像上面的StackPanel示例一样,里面的所有内容都保持原样。
我为什么还要打扰UserControl,并且如果不执行任何操作又要创建和渲染另一个项目呢?
的目的UserControl
是要组一组控制成一个,可重复使用的部件。它们不能设置样式或模板。
a的目的Custom Control
是扩展现有控件或创建全新的控件。与a相对,UserControl
可以对它们进行样式设置和模板化。
我认为您将两者混为一谈。
因此,您可能想知道,“我何时应使用a UserControl
,何时应使用a Custom Control
?”。答案是取决于。
UserControl
当您需要创建逻辑控件组时,应该使用,这些控件以某种方式交互以创建几乎复合的控件。Custom Control
要将功能添加到现有控件时,应使用a 。
在您的示例中,最好的方法是使用UserControl
,因为将StackPanel
一组控件组合成一个可重用的组件。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句