使用TextBox和Button的自定义控件不会从父级继承样式

时间:2019-05-23 17:00:22

标签: c# wpf user-controls wpf-controls

我用TextBox和Button创建了一个用户控件,但它不想使用父级的样式。但是,我的控件在设计时就希望具有父级的样式,但是在运行时样式会消失。

有我的TextBoxButton.xaml

 <Style x:Key="{x:Type Common:TextBoxExtension}" TargetType="{x:Type Common:TextBoxExtension}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Common:TextBoxExtension}">
                <Border x:Name="border" 
                        Background="{TemplateBinding Background}" 
                        BorderBrush="{TemplateBinding BorderBrush}"
                        BorderThickness="{TemplateBinding BorderThickness}"
                        SnapsToDevicePixels="True">
                    <DockPanel>
                        <Button DockPanel.Dock="Right" Padding="-3.0" Margin="2"
                                Width="{Binding ActualHeight, RelativeSource={RelativeSource AncestorType={x:Type TextBoxBase},Mode=FindAncestor}}"
                                Content="..."
                                HorizontalContentAlignment="Center"
                                VerticalContentAlignment="Center"
                                Command="{TemplateBinding Command}"/>
                        <ScrollViewer Name="PART_ContentHost" Focusable="False"
                                      HorizontalScrollBarVisibility="Hidden"
                                      VerticalScrollBarVisibility="Hidden"/>
                    </DockPanel>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

此外,还有TextBoxExtension.cs

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

    public static readonly DependencyProperty CommandProperty = 
        DependencyProperty.Register("Command", typeof(ICommand), typeof(TextBoxExtension), 
        new PropertyMetadata(null));

    public ICommand Command
    {
        get { return (ICommand)GetValue(CommandProperty); }
        set { SetValue(CommandProperty, value); }
    }
}

在窗口中使用

<Common:TextBoxExtension FontSize="14" Text="{Binding VaultPath, UpdateSourceTrigger=PropertyChanged}" Margin="5" Grid.Column="1" Grid.Row="2" />
<Common:TextBoxExtension FontSize="14" Command="{Binding SetLocalPath}" Text="{Binding LocalPath, UpdateSourceTrigger=PropertyChanged}" Margin="5" Grid.Column="1" Grid.Row="3" />

我期望得到的东西

ExpectedImage

我在运行程序时得到了什么

RealResults

想要添加按钮可以正常工作

0 个答案:

没有答案