在WPF自定义控件中,是否可以将子元素与模板绑定到控件的事件?

时间:2010-10-28 12:31:53

标签: c# events xaml custom-controls binding

我有一个自定义控件,其中包含两个可以单击的元素(一个按钮和一个复选框)。我希望能够在XAML中为每个事件添加事件。

即。

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

我不知道如何绑定这样的事件。有什么指针吗?

以下是用户控件的内容:

<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>

1 个答案:

答案 0 :(得分:1)

您需要将孩子的事件路由到您的顶级元素 在顶部元素的代码隐藏中,定义您需要的RoutedEvent。然后,在构造函数中,订阅子项所需的事件,并在处理程序中,使用相同的args抛出与处理的子事件对应的新top元素事件。

实施例

注意:在Google上查找自定义路由事件。在这个例子中,你仍然需要复制按钮事件参数(如果你需要它们,以获得对当前按钮状态的访问等)到被吹捧的事件。

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);
    }
}
相关问题