wpf - 使用子元素创建 WPF 用户控件

标签 wpf user-controls

我尝试创建一个“容器”用户控件,它可以在 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/

相关文章:

WPF 绑定(bind)到 UserControl 自定义 DependencyProperty

c# - 在 C#/.NET 2.0 中控制双缓冲所有者绘制的 UserControl 的设计器外观

c# - 在 WPF 中加载数据时显示 Mahapps.ProgressRing

c# - 必须使用什么命名空间来获取 DataGridComboBoxColumn?

c# - 当存储在 Application.Resources 中时,为什么 Freezables 已经被卡住并且有一个空的 Dispatcher(与 Styles 相同)?

c# - Unity3D C#。使用 transform.RotateAround() 函数同时保持两个对象之间的距离不变

c# - 不同 usercontrol.ascx 中的两个验证按钮

WPF - ItemTemplate 未按预期运行

WPF 事件触发器 - 无法将属性 'MouseEnter' 中的字符串 'RoutedEvent' 转换为 'System.Windows.RoutedEvent' 类型的对象

python - 使用 python 设置背景图像