我尝试创建一个“容器”用户控件,它可以在 WPF 中将 UIElement
对象显示为子对象。控件的用法应如下所示:
<general:DisplayContainer Title="Hello">
<TextBlock x:Name="AnyUIElement" />
</general:DisplayContainer>
TextBlock 只是一个例子。到目前为止,我创建了 UserControl 并像这样绑定(bind) Title 属性:
<Grid x:Name="Grid_Main">
<Border x:Name="Border_Main" BorderThickness="2" Margin="10" CornerRadius="5" Padding="7" />
<TextBlock x:Name="TextBlock_Title" Background="{Binding Background, ElementName=Grid_Main}" HorizontalAlignment="Left" VerticalAlignment="Top" Text="{Binding Path=Title, FallbackValue=Title}" Margin="20,2,0,0" Padding="3,0" />
</Grid>
代码隐藏文件如下所示:
public partial class DisplayContainer : UserControl
{
public DisplayContainer()
{
InitializeComponent();
this.DataContext = this;
}
public string Title
{
get { return (string)GetValue(TitleProperty); }
set { SetValue(TitleProperty, value); }
}
public static readonly DependencyProperty TitleProperty =
DependencyProperty.Register("Title",typeof(string), typeof(DisplayContainer));
}
现在,我如何修改我的控件,以便在我使用控件时接受 XAML 文件中的子元素?应通过 Border_Main.Child
属性显示子项。
提前致谢,
弗兰克
最佳答案
只需设置 UserControl 的 Template 属性
<UserControl ...>
<UserControl.Template>
<ControlTemplate TargetType="UserControl">
<StackPanel>
<TextBlock Text="{Binding Title,
RelativeSource={RelativeSource AncestorType=UserControl}}"/>
<ContentPresenter />
</StackPanel>
</ControlTemplate>
</UserControl.Template>
</UserControl>
并将显示的元素放在用户控件的内容中:
<local:DisplayContainer Title="A Title">
<TextBlock Text="Hello"/>
</local:DisplayContainer>
关于wpf - 使用子元素创建 WPF 用户控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49651570/