WPF list style with button

I have a ListBox that has a style defined for ListBoxItems. Inside this style, I have shortcuts and a button. One of these buttons, I want to define a click event that can be processed on my page (or on any page using this style). How to create an event handler on my WPF page to handle an event from my ListBoxItems style?

Here is my style (code only):

<Style x:Key="UsersTimeOffList" TargetType="{x:Type ListBoxItem}"> ... <Grid> <Button x:Name="btnRemove" Content="Remove" Margin="0,10,40,0" Click="btnRemove_Click" /> </Grid> </Style> 

Thanks!

+7
c # wpf
source share
3 answers

See RoutedCommand s.

Define your command in myclass somewhere as follows:

  public static readonly RoutedCommand Login = new RoutedCommand(); 

Now define your button with this command:

  <Button Command="{x:Static myclass.Login}" /> 

You can use CommandParameter for more information.

Now, but just as importantly, start listening to your command:

In the class constructor you want to do something nice, you put:

  CommandBindings.Add(new CommandBinding(myclass.Login, ExecuteLogin)); 

or in XAML:

  <UserControl.CommandBindings> <CommandBinding Command="{x:Static myclass.Login}" Executed="ExecuteLogin" /> </UserControl.CommandBindings> 

And you implement the delegate that needs CommandBinding:

  private void ExecuteLogin(object sender, ExecutedRoutedEventArgs e) { //Your code goes here... e has your parameter! } 

You can start listening to this command everywhere in your visual tree!

Hope this helps

PS You can also define a CommandBinding with a CanExecute delegate that will even disable your command if CanExecute says so :)

PPS Here is another example: RoutedCommands in WPF

+10
source share

As Arcturus wrote, RoutedCommands is a great way to achieve this. However, if there is only one button in your DataTemplate, this might be a little easier:

In fact, you can handle any button. Click an event from the host ListBox list, for example:

 <ListBox Button.Click="removeButtonClick" ... /> 

Any buttons contained in the ListBox will trigger this event when clicked. Inside the event handler, you can use e.OriginalSource to return the link to the button that the button was clicked on.

Obviously, this is too simplified if there are several buttons in the ListBoxItems, but in many cases this works just fine.

+6
source share

You can create a custom control (.ascx) to place the list. Then add a public event for the page.

 Public Event btnRemove() 

Then in the button click event in usercontrol

 RaiseEvent btnRemove() 

You can also pass objects through an event just like any other method. This will allow your user to control the message on your page about what needs to be deleted.

0
source share

All Articles