This article has been localized into Chinese by the community.
If you are fluent in Chinese, then please help us - just point to any untranslated element (highlighted with a yellow left border - remember that images should have their titles translated as well!) inside the article and click the translation button to get started. Or have a look at the current translation status for the Chinese language.
If you see a translation that you think looks wrong, then please consult the original article to make sure and then use the vote button to let us know about it.
Metadata
Please help us by translating the following metadata for the article/chapter, if they are not already translated.
If you are not satisfied with the translation of a specific metadata item, you may vote it down - when it reaches a certain negative threshold, it will be removed.
Please only submit an altered translation of a metadata item if you have good reasons to do so!
Please login to translate metadata!
Already logged in? Please try reloading the page!
More info...
Looking for the original article in English?
用户控件和自定义控件:
创建和使用用户控件在WPF中由UserControl类表示,用户控件是将标记和代码分组到可重用容器中的概念,因此具有相同界面相同功能,可以在几个不同的位置使用,甚至可以在多个应用程序中使用。
用户控件的行为很像WPF窗口 - 您可以放置其他控件的区域,然后是可以与这些控件交互的代码后置文件。 包含用户控件的文件也以.xaml结尾,而代码后置以.xaml.cs结尾 - 就像一个Window。 起始标记虽然看起来有点不同:
创建用户控件通过右键单击要添加它的项目或文件夹名称,向项目添加用户控件,就像添加另一个Window一样,如此截图所示(可能看起来有点不同,具体取决于您正在使用的Visual Studio版本):
在这篇文章中,我们将创建一个有用的用户控件,能够将TextBox中的文本数量限制为特定数量的字符,同时向用户显示已使用的字符数以及可以使用的字符数。 这很简单,并且在许多Web应用程序(如Twitter)中使用。 将这个功能添加到常规窗口很容易,但由于它可能在应用程序的多个位置使用,因此将它包装在一个易于重用的UserControl中是有意义的。
在我们深入研究代码之前,让我们看一下我们的最终结果:
这是用户控件本身的代码:
当前字符计数是通过直接绑定到TextBox控件上的Text.Length属性获得的,该控件使用用户控件的下半部分。 结果可以在上面的截图中看到。 请注意,由于所有这些绑定,我们不需要任何C#代码来更新标签或在TextBox上设置MaxLength属性 - 相反,我们只是直接绑定到属性。
消费/使用用户控件有了上面的代码,我们所需要的就是在Window中消费(使用)用户控件。 我们将通过在Window的XAML代码的顶部添加对UserControl所在的命名空间的引用来实现:
xmlns:uc="clr-namespace:WpfTutorialSamples.User_Controls"之后,我们可以使用uc前缀将控件添加到我们的Window,就像任何其他WPF控件一样:
小结强烈建议在用户控件中放置常用的界面和功能,正如您在上面的示例中所看到的,它们非常易于创建和使用。
Introduction
Previous
Introduction to WPF data binding
Next
This article has been fully translated into the following languages:
Albanian
Chinese
Czech
Dutch
French
German
Italian
Japanese
Polish
Portuguese
Russian
Spanish
Turkish
Ukrainian
Vietnamese
Is your preferred language not on the list? Click here to help us translate this article into your language!