<ItemsControl x:Class="HDSProject.Control.CustomFont" 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:HDSProject.Control" mc:Ignorable="d" d:DesignHeight="450" d:DesignWidth="800" x:Name="itemCtrl" ItemsSource="{Binding Path=Title2, RelativeSource={RelativeSource Mode=Self}}" FontSize="20" Foreground="Teal" > <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <StackPanel Orientation="Horizontal"/> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> <ItemsControl.ItemTemplate> <DataTemplate> <StackPanel> <Border Margin="{Binding Path=CharacterSpacing, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=local:CustomFont}}"> <TextBlock Text="{Binding}" /> </Border> <Rectangle Height="1" Fill="{Binding Foreground, ElementName=itemCtrl}" Margin="0,0,0,5"> <Rectangle.Style> <Style TargetType="Rectangle"> <Setter Property="Visibility" Value="Collapsed" /> <Style.Triggers> <DataTrigger Binding="{Binding ShowUnderline, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=local:CustomFont}}" Value="True"> <Setter Property="Visibility" Value="Visible" /> </DataTrigger> </Style.Triggers> </Style> </Rectangle.Style> </Rectangle> </StackPanel> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl>这是个自定控件,我在后台声明了一个Border对象,怎么让Border对象包裹这个控件
时间: 2024-02-14 20:10:07 浏览: 48
gong-wpf-dragdrop:GongSolutions.WPF.DragDrop库是WPF的拖放框架
你可以在自定义控件的代码中找到ItemsControl,并将其包含在一个Border中,然后设置Border的边框、背景等属性,使其包裹住ItemsControl。具体代码如下:
```csharp
public class CustomFont : Control
{
private Border border;
public CustomFont()
{
this.DefaultStyleKey = typeof(CustomFont);
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
// 找到ItemsControl
var itemsControl = GetTemplateChild("itemCtrl") as ItemsControl;
if (itemsControl != null)
{
// 创建一个Border
border = new Border();
// 把ItemsControl放入Border中
border.Child = itemsControl;
// 设置Border的边框、背景等属性
border.BorderThickness = new Thickness(1);
border.BorderBrush = Brushes.Black;
border.Background = Brushes.White;
// 将Border加入自定义控件的视觉树中
this.AddVisualChild(border);
}
}
protected override int VisualChildrenCount
{
get { return border != null ? 1 : 0; }
}
protected override Visual GetVisualChild(int index)
{
if (index == 0 && border != null)
{
return border;
}
else
{
throw new ArgumentOutOfRangeException("index");
}
}
}
```
这样就可以让Border对象包裹住CustomFont自定义控件了。需要注意的是,在自定义控件的代码中,我们需要重载VisualChildrenCount和GetVisualChild方法,以便正确地处理自定义控件的视觉树。
阅读全文