views:

16

answers:

1

I have a custom control that contains two elements that can be clicked (a button and a check box). I'd like to be able to put events in the XAML for each of these events.

i.e.

<Control OnButtonClick="SomeEvent"  OnCheckBoxClick="SomeOtherEvent" />

I have no idea how to bind events like that. Any pointers?

The following is the content of the user control:

<Style TargetType="{x:Type local:DeleteCheckBox}">
    <Setter Property="Template">
    <Setter.Value>
        <ControlTemplate TargetType="{x:Type local:DeleteCheckBox}">
            <Grid>
                <Label Height="25" BorderBrush="LightGray" BorderThickness="1" Padding="0" DockPanel.Dock="Top" FlowDirection="RightToLeft" Visibility="Hidden">
                    <Button x:Name="ImageButton1" Background="Transparent" Padding="0" BorderBrush="Transparent" Height="11" Width="11" Click="--Bind Function Here--" />
                </Label>
                <CheckBox Content="A0000" Click="--Bind Function Here--" IsChecked="True" Margin="0,10,10,0" VerticalContentAlignment="Center"/>
            </Grid>
        </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>
A: 

You need to route the events from your children to your top element.
In the code-behind of your top element, define the RoutedEvents you need. Then, in the constructor, subscribe to your children required events, and in the handlers, throw a new top-element event corresponding to your handled child event with the same args.

Example

Note: Look for custom routed events on google. In this example, you still need to copy the button event arguments (if you need them, to get access to current button state, etc) to the touted event.

public class MyCustomControl : UserControl {
    // Custom routed event
    public static readonly RoutedEvent ButtonClickEvent = EventManager.RegisterRoutedEvent(
        "ButtonClick", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(MyCustomControl));

    // Custom CLR event associated to the routed event
    public event RoutedEventHandler ButtonClick {
        add { AddHandler(ButtonClickEvent, value); } 
        remove { RemoveHandler(ButtonClickEvent, value); }
    }

    // Constructor. Subscribe to the event and route it !
    public MyCustomControl() {
        theButton.Click += (s, e) => {
            RaiseButtonClickEvent(e);
        };
    }

    // Router for the button click event
    private void RaiseButtonClickEvent(RoutedEventArgs args) {
        // you need to find a way to copy args to newArgs (I never tried to do this, google it)
        RoutedEventArgs newArgs = new RoutedEventArgs(MyCustomControl.ButtonClickEvent);
        RaiseEvent(newArgs);
    }
}
Aurélien Ribon