Hello,
Welcome to Microsoft Q&A!
How to bind "command" and "CommandParameter" of a button in template(WinUI3)?
What you need now is to create a command in the TestListBoxItem
. And change the binding of the Button from x:Bind
to Binding
. You could refer to the following code:
Xaml
// the xaml code will pass the textblock as parameter. Just an example.
<Button Command="{Binding DeleteCommand}" CommandParameter="{Binding ElementName=Label}">Delete</Button>
C# Code
public class TestListBoxItem : INotifyPropertyChanged
{
public event PropertyChangedEventHandler? PropertyChanged;
public string ItemName { get; set; }
public string Id { get; set; }
public TestListBoxItem()
{
Id = "";
ItemName = "";
}
private void FirePropertyChanged(string propertyName)
{
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
// create a delete command which used for binding
public ICommand DeleteCommand
{
get
{
return new CommadEventHandler<object>((obj) => this.DeleteSomething(obj));
}
}
// delete method
private void DeleteSomething(object obj)
{
try
{
Debug.WriteLine("DeleteSomething");
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
}
// custom command with parameter
public class CommadEventHandler<T> : ICommand
{
public event EventHandler CanExecuteChanged;
public Action<T> action;
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
this.action((T)parameter);
}
public CommadEventHandler(Action<T> action)
{
this.action = action;
}
}
Thank you.
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.