How to make a wpf usercontrol with events(with Microsoft.Xaml.Behaviours.Wpf command) and dependecy properties?

32 Views Asked by At

I want to make a UserControl that has his own custom event and custom DependencyProperty

I have this code that works fine:
UserControl1.xaml.cs:

public partial class UserControl1 : UserControl
{
    // Custom DependencyProperty
    public string CustomText
    {
        get { return (string)GetValue(CustomTextProperty); }
        set { SetValue(CustomTextProperty, value); }
    }

    public static readonly DependencyProperty CustomTextProperty =
        DependencyProperty.Register("CustomText", typeof(string), typeof(UserControl1));

    // Custom Event
    public event RoutedEventHandler CustomClick
    {
        add { AddHandler(CustomClickEvent, value); }
        remove { RemoveHandler(CustomClickEvent, value); }
    }

    public static readonly RoutedEvent CustomClickEvent =
        EventManager.RegisterRoutedEvent("CustomClick", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(UserControl1));

    protected virtual void OnClick(object sender, RoutedEventArgs e) => RaiseEvent(new RoutedEventArgs(CustomClickEvent));

    public UserControl1()
    {
        InitializeComponent();
        DataContext = this;
    }
}

UserControl1.xaml:

<UserControl x:Class="WpfApp1.UserControl1"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:WpfApp1"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             d:DesignHeight="450"
             d:DesignWidth="800"
             mc:Ignorable="d">

    <Grid>
        <Button Click="OnClick"
                Content="{Binding CustomText}" />
    </Grid>

</UserControl>

But if I want to track my custom CustomClick event with Microsoft.Xaml.Behaviours.Wpf, command isn't working but event is tracking. I mean this:
MainWindow.xaml:

<local:UserControl1 xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
                    CustomText="Hello">

    <i:Interaction.Triggers>

        <i:EventTrigger EventName="CustomClick">

            <i:InvokeCommandAction Command="{Binding Command}" />

        </i:EventTrigger>

    </i:Interaction.Triggers>

</local:UserControl1>

MainWindow.xaml.cs:

public partial class MainWindow : Window
{
    public ICommand Command { get; } = new RelayCommand(obj => MessageBox.Show("Hello from Command"));

    public MainWindow()
    {
        InitializeComponent();
        DataContext = this;
    }
}

What am i doing wrong?

Note: If i remove DataContext = this from UserControl then Command will work, but custom property CustomText won't be bound to button content in UserControl

0

There are 0 best solutions below