Converting a UserControl to a Custom Control

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-06 07:17:11

Here's an example of a custom button with a tooltip (based on the questions you've been asking recently):

This is the code

public class CustomButton : Button
{
    static CustomButton()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomButton), 
           new FrameworkPropertyMetadata(typeof(CustomButton)));
    }

    public static readonly DependencyProperty SubjectProperty =
        DependencyProperty.Register("Subject", typeof (string),
        typeof (CustomButton), new PropertyMetadata(default(string)));

    public string Subject
    {
        get { return (string) GetValue(SubjectProperty); }
        set { SetValue(SubjectProperty, value); }
    }
}

This goes in Themes/generic.xaml

<System:String x:Key="Test">Add new: </System:String>

<Style TargetType="{x:Type local:CustomButton}">
    <Setter Property="ToolTip" 
            Value="{Binding RelativeSource={RelativeSource Self}, Path=Subject}"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type local:CustomButton}">
                <Border Background="{TemplateBinding Background}"
                        BorderBrush="{TemplateBinding BorderBrush}"
                        BorderThickness="{TemplateBinding BorderThickness}">
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="Auto"/>
                            <ColumnDefinition/>
                        </Grid.ColumnDefinitions>

                        <Label Grid.Column="0" Content="Image here" 
                               VerticalAlignment="Center" Padding="0,0,5,0"/>

                        <AccessText Grid.Column="1" VerticalAlignment="Center">
                            <AccessText.Text>
                                <MultiBinding StringFormat="{}_{0} {1}">
                                    <Binding Source="{StaticResource Test}"/>
                                    <Binding RelativeSource=
                                        "{RelativeSource TemplatedParent}" 
                                        Path="Subject"/>
                                </MultiBinding>
                            </AccessText.Text>
                        </AccessText>
                    </Grid>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!