2

XAML код UserControl'а:

     <UserControl x:Class="UsersObjects.Styles.UserControls.VectorButton"
             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:UsersObjects.Styles.UserControls"
             mc:Ignorable="d" 
             d:DesignHeight="50" d:DesignWidth="50" x:Name="uc">
    <UserControl.Resources>
        <Style TargetType="local:VectorButton">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="local:VectorButton">
                        <Button Style="{StaticResource Button.Transparent}" WindowChrome.IsHitTestVisibleInChrome="True" 
                                Command="{Binding Command, ElementName=uc}"
                                CommandParameter="{Binding CommandParameter, ElementName=uc}">
                            <Viewbox Width="{TemplateBinding Width}" Height="{TemplateBinding Height}">
                                <Canvas Width="25" Height="25">
                                    <Path Fill="{TemplateBinding Foreground}"
                                          Data="{Binding Path, ElementName=uc}" />
                                </Canvas>
                            </Viewbox>
                        </Button>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </UserControl.Resources>
</UserControl>

XAML код стиля словаря ресурсов Controls.xaml:

<Style x:Key="RemoveButton" TargetType="{x:Type uc:VectorButton}">
        <Setter Property="Opacity" Value="1"/>
        <Setter Property="Foreground" Value="Black"/>
        <Setter Property="Path" Value="M3,16.74L7.76,12L3,7.26L7.26,3L12,7.76L16.74,3L21,7.26L16.24,12L21,16.74L16.74,21L12,16.24L7.26,21L3,16.74M12,13.41L16.74,18.16L18.16,16.74L13.41,12L18.16,7.26L16.74,5.84L12,10.59L7.26,5.84L5.84,7.26L10.59,12L5.84,16.74L7.26,18.16L12,13.41Z"/>
        <Setter Property="Cursor" Value="Hand"/>
       
    </Style>

XAML код в MainWindow.xaml:

      <Grid>
         <uc:VectorButton Style="{StaticResource RemoveButton}" Margin="220,0,0,40"  Width="30" Height="30"/>
       </Grid>

Стиль не применяется, UserControl как будто вовсе отсутствует.

UPD: CodeBehind UserControl'а:

 public partial class VectorButton : UserControl
        {
            public VectorButton() => InitializeComponent();
    
            public Geometry Path
            {
                get => (Geometry)GetValue(PathProperty);
                set => SetValue(PathProperty, value);
            }
    
            public static readonly DependencyProperty PathProperty =
                DependencyProperty.Register("Path", typeof(Geometry), typeof(VectorButton), new PropertyMetadata(Geometry.Parse("M13,14H11V10H13M13,18H11V16H13M1,21H23L12,2L1,21Z")));
    
    
            public ICommand Command
            {
                get => (ICommand)GetValue(CommandProperty);
                set => SetValue(CommandProperty, value);
            }
    
            public static readonly DependencyProperty CommandProperty =
                DependencyProperty.Register("Command", typeof(ICommand), typeof(VectorButton));
    
    
    
            public object CommandParameter
            {
                get => GetValue(CommandParameterProperty);
                set => SetValue(CommandParameterProperty, value);
            }
    
            public static readonly DependencyProperty CommandParameterProperty =
                DependencyProperty.Register("CommandParameter", typeof(object), typeof(VectorButton));
        }

Стиль Button.Transparent:

 <Style x:Key="Button.Transparent" TargetType="Button">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="Button">
                        <Border Background="Transparent" Cursor="Hand">
                            <ContentPresenter Content="{TemplateBinding Content}"/>
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
13
  • А где вы подключаете словарь ресурсов из Controls.xaml? metanit.com/sharp/wpf/9.3.php
    – aepot
    2 мая 2021 в 18:14
  • Я не про пространство имен, а про ResourceDictionary в файле Controls.xaml. Откройте ссылку выше.
    – aepot
    2 мая 2021 в 18:27
  • 1
    Добавил codebehind юзерконтрола и стиль Button.Transparent
    – VeNNoM
    2 мая 2021 в 19:19
  • 1
    Правил, uc - само имя юзерконтрола.
    – VeNNoM
    2 мая 2021 в 19:26
  • 1
    Вернул, убрал из него анимацию.
    – VeNNoM
    2 мая 2021 в 19:31

1 ответ 1

3

Здесь несколько пробелем

  1. Марджины сплющивают кнопку, не используйте никогда марджины из дизайнера
<Grid>
    <uc:VectorButton Style="{StaticResource RemoveButton}" Width="30" Height="30"/>
</Grid>
  1. Стиль, назначаемый контролу переопределяет стиль, назначенный внутри контрола. Следовательно, нужно либо назначать только свойства без стиля, либо уходить от ControlTemplate.

Получается такая разметка юзерконтрола

<UserControl x:Class="WpfApp2.VectorButton"
             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" 
             mc:Ignorable="d" 
             d:DesignHeight="50" d:DesignWidth="50">
    <Button Style="{StaticResource Button.Transparent}" 
            WindowChrome.IsHitTestVisibleInChrome="True" 
            DataContext="{Binding RelativeSource={RelativeSource AncestorType=UserControl}}"
            Command="{Binding Command}"
            CommandParameter="{Binding CommandParameter}">
        <Viewbox>
            <Canvas Width="25" Height="25">
                <Path Fill="{Binding Foreground}"
                      Data="{Binding Path}" />
            </Canvas>
        </Viewbox>
    </Button>
</UserControl>

Без встроенных ресурсов.

введите сюда описание изображения

1
  • 1
    Спасибо, работает!
    – VeNNoM
    2 мая 2021 в 20:30

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.