zl程序教程

您现在的位置是:首页 >  .Net

当前栏目

wpf使用usercontrol自定义标签

2023-04-18 12:44:06 时间

自定义标签

想向js一样自定义一个组件,过程很复杂,并没有js那样好操作,直接上代码吧,

   <UserControl.ContentTemplate>
        <DataTemplate>
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="25"/>
                    <RowDefinition Height="*"/>
                </Grid.RowDefinitions>
                <Grid Background="#1979ca" Grid.Row="0">
                    <TextBox Name="title" Text="{Binding Header,ElementName=comstom}" Background="Transparent" HorizontalAlignment="Left" 
                         Foreground="White" VerticalAlignment="Center" BorderThickness="0"/>
                    <Image Source="Resource/a.png" HorizontalAlignment="Right" Margin="6,0" Height="18" MouseLeftButtonDown="Image_MouseLeftButtonDown"/>
                </Grid>
                <ContentPresenter Content="{Binding}" Grid.Row="1" />
            </Grid>
        </DataTemplate>
    </UserControl.ContentTemplate>

自定义属性

public static DependencyProperty HeaderProperty =
    DependencyProperty.Register("Header", typeof(string), typeof(TitleWindow), new PropertyMetadata(""));
public string Header
{
     get { return (string)GetValue(HeaderProperty); }
     set{SetValue(HeaderProperty, value);}
}

讲解

使用模板contenttemplate,重写usercontrol,而不是在usercontrol里面直接加grid等标签,最后uesrcontrol的content通过

<ContentPresenter Content="{Binding}" Grid.Row="1" />

直接被转移到了一个新的节点上

或者通过loaded消息,在加载后,修改content的节点,否则同一个节点在两个父节点下会报错的。