我希望在XAML中设置一个UserControl成为Content另一个UserControl,就像你可以设置Button's Content为任何东西一样.
假设我的"外部" UserControl看起来像这样:
<MyUserControl>
<Grid>
<Border FancyPantsStyling="True">
<-- I want to insert other controls here -->
</Border>
</Grid>
</MyUserControl>
Run Code Online (Sandbox Code Playgroud)
我想以这种方式实例化:
<local:MyUserControl>
<local:MyUserControl.Content>
<local:AnotherControl />
</local:MyUserControl.Content>
</local:MyUserControl>
Run Code Online (Sandbox Code Playgroud)
如何设计MyUserControl将其渲染Content到特定位置?
您放入 UserControl 的 XAML 中的所有内容都是其内容,因此您无法通过设置 Content 属性来注入其他内容。有几种不同的方法可以处理这个问题。如果 MyUserControl 的代码隐藏中没有任何内容,您可以删除它并使用类似以下内容的内容:
<ContentControl>
<ContentControl.Template>
<ControlTemplate TargetType="{x:Type ContentControl}">
<Grid>
<Border FancyPantsStyling="True">
<ContentPresenter/>
</Border>
</Grid>
</ControlTemplate>
</ContentControl.Template>
<local:AnotherControl/>
</ContentControl>
Run Code Online (Sandbox Code Playgroud)
如果您的后台代码不能直接访问 XAML 元素,您可以对现有控件执行类似的操作(因为 UC 派生自 ContentControl):
<local:MyUserControl>
<local:MyUserControl.Template>
<ControlTemplate TargetType="{x:Type local:MyUserControl}">
<Grid>
<Border FancyPantsStyling="True">
<ContentPresenter/>
</Border>
</Grid>
</ControlTemplate>
</local:MyUserControl.Template>
</local:MyUserControl>
Run Code Online (Sandbox Code Playgroud)
如果您需要将现有内容保持连接到代码隐藏,您可以使用 DataTemplate 传入外部内容(到 MyUserControl 上的新 DP 中),并将该模板应用于 UC 的 XAML 中的 ContentControl。
| 归档时间: |
|
| 查看次数: |
11929 次 |
| 最近记录: |