我正在尝试在WPF / XAML中创建一个“标题块”UserControl,其行为如下:
控制声明如下:
<Border x:Name="LayoutRoot" Background="#4C000000" CornerRadius="10" Padding="10">
<DockPanel>
<TextBlock Text="Some Title" DockPanel.Dock="Top" />
</DockPanel>
</Border>
预期用法是这样的:
<Grid x:Name="LayoutRoot" Background="White">
<local:Bloco Height="100" Width="100" Title="Other Title">
<local:Bloco Title="Yet other title" />
</local:Bloco>
</Grid>
要渲染这样的东西:
但实际当前渲染无效。问题是:
感谢阅读!
答案 0 :(得分:4)
答案 1 :(得分:3)
通用用户控件:
XAML:
<UserControl x:Class="WpfControlLibrary.GenericUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:WpfControlLibrary"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300" x:Name="Control">
<UserControl.Resources>
<Style TargetType="{x:Type local:GenericUserControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:GenericUserControl}">
<Grid Background="{Binding Background, ElementName=Control}">
<Grid.RowDefinitions>
<RowDefinition Height="5"></RowDefinition>
<RowDefinition Height="20"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="5"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="5"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="5"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="1" Grid.Row="1" Text="{Binding Title, ElementName=Control}"/>
<ContentPresenter Grid.Column="1" Grid.Row="2"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</UserControl.Resources>
代码背后:
namespace WpfControlLibrary
{
public partial class GenericUserControl
{
public string Title
{
get { return (string)GetValue(TitleProperty); }
set { SetValue(TitleProperty, value); }
}
public static readonly DependencyProperty TitleProperty =
DependencyProperty.Register("Title", typeof(string), typeof(GenericUserControl), new PropertyMetadata(string.Empty));
public GenericUserControl()
{
InitializeComponent();
}
}
}
而不是像这样使用用户控件:
<wpfControlLibrary:GenericUserControl Title="Other Title" Background="LightGray">
<wpfControlLibrary:GenericUserControl Title="Yet Another Title" Background="Gray"/>
</wpfControlLibrary:GenericUserControl>