PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, November 21, 2022

[FIXED] How to bind a method for custom dependency property via user control?

 November 21, 2022     c#, visual-studio, windows, winui-3, xaml     No comments   

Issue

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);
   }
}

Solution

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>


Answered By - Andrew KeepCoding
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing