如何在XAML中设计应用程序的一部分,然后如何重复使用它?[英] How to design parts of the application in XAML and how to reusing it then?

本文是小编为大家收集整理的关于如何在XAML中设计应用程序的一部分,然后如何重复使用它?的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我正在我的应用程序中处理一个主窗口,我想在 Visual Studio 设计器中单独设计我的窗口的一部分.

主窗口

  • 游戏桌(实际上更多,因此最好设计游戏桌,将其标记为资源,然后通过简单的代码(例如创建新对象和设置 DataContext)创建它.
  • 控制台
  • 等等

在VS中可以做这件事吗?

如果可能的话,我只需要知道要寻找什么.我不需要完整的解决方案.

感谢您的建议!

推荐答案

ItemTemplates 或 UserControls 可能是您正在寻找的.

您可以为集合中的事物创建 ItemTemplate,以便它们自动以一种或另一种方式显示,并且您可以直接绑定到由 ItemTemplate 表示的类中的数据.

通常,我喜欢创建一个新的 UserControl.您基本上使用 XAML 创建了一个新控件.然后,您可以创建实例并按照您所说的设置每个实例的数据上下文.

您甚至可以在其他 XAML 项目中使用它.只要确保添加命名空间.类似:

xmlns:lp="clr-namespace:LocalProject"

然后像其他控件一样使用它:

<StackPanel>
    <lp:YourUserControl DataContext="bind to an object of the correct type here" />
</StackPanel>

并且在后面的代码中,您将能够访问绑定的 DataContext 对象:

YourCustomClass cc = this.DataContext as YourCustomClass;

本文地址:https://www.itbaoku.cn/post/627344.html

问题描述

I'm working on a main window in my application and I would like to design parts of my window separately in Visual Studio designer.

Main window

  • Game desk (actually more of them and therefore it would be nice to design the game desk, mark it as a resource and then just via simple code (something like creating a new object and setting DataContext) create it.
  • Console
  • And so on

Is it possible in VS to do this thing?

I just need to know what to look for if it is possible. I don't need a whole solution.

Thank you for suggestions!

推荐答案

ItemTemplates or UserControls are probably what you are looking for.

You can create ItemTemplates for things in a collection so they automatically get displayed one way or another and you can bind directly to the data in the class that is being represented by your ItemTemplate.

Often, I like to create a new UserControl instead. You basically create a new control with XAML. Then you can create instances and set the datacontext of each as you stated you'd like to do.

You can even use it in other XAML projects. Just be sure to add the namespace.Something like:

xmlns:lp="clr-namespace:LocalProject"

Then use it just like your other controls:

<StackPanel>
    <lp:YourUserControl DataContext="bind to an object of the correct type here" />
</StackPanel>

And in the code behind you'll be able to access the bound DataContext object:

YourCustomClass cc = this.DataContext as YourCustomClass;