Home > database >  How to bind a method for custom dependency property via user control?
How to bind a method for custom dependency property via user control?

Time:10-27

I currently have a Button inside my custom UserControl that needs to have a method name binded to it's Click dependency, the method name being provided from a custom dependency property in the user control. Any ideas on how to do this?

Page.xaml

<local:CustomButton OnClick="CustomButton1_Click" ... />

Page.xaml.cs

private void CustomButton1_Click(object sender, RoutedEventArgs e)
{
    // do something...
}

CustomButton.xaml

<Button Click={x:Bind OnClick} ... />

CustomButton.xaml.cs

public sealed partial class CustomButton : UserControl
{
   ...
   
   public static readonly DependencyProperty OnClickProperty = DependencyProperty.Register("OnClick", typeof(string), typeof(CustomButton), new PropertyMetadata(true));
    
   public bool IsNavigator
   {
       get => (string)GetValue(OnClickProperty);
       set => SetValue(OnClickProperty, value);
   }
}

CodePudding user response:

Do you mean you want to call CustomButton1_Click when CustomButton is clicked?

CustomButton.xaml

<UserControl
    x:Class="UserControls.CustomButton"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:UserControls"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid>
        <Button Content="Button" Click="Button_Click"/>
    </Grid>
</UserControl>

CustomButton.xaml.cs

using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using System;

namespace UserControls;

public sealed partial class CustomButton : UserControl
{
    public CustomButton()
    {
        this.InitializeComponent();
    }

    public event EventHandler? OnClick;

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        OnClick?.Invoke(this, EventArgs.Empty);
    }
}

And use it like this:

<Grid>
    <local:CustomButton OnClick="CustomButton_OnClick" />
</Grid>
  • Related