【问题标题】:In a WPF custom control, is it possible for a child element to Template bind to the event of the control?在 WPF 自定义控件中,子元素是否可以模板绑定到控件的事件?
【发布时间】:2010-10-28 12:31:52
【问题描述】:

我有一个自定义控件,其中包含两个可以单击的元素(一个按钮和一个复选框)。我希望能够将每个事件的事件放在 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>

【问题讨论】:

    标签: c# events xaml custom-controls binding


    【解决方案1】:

    您需要将事件从您的孩子路由到您的顶级元素。
    在顶部元素的代码隐藏中,定义您需要的 RoutedEvents。然后,在构造函数中,订阅您的孩子所需的事件,并在处理程序中,抛出一个新的顶级元素事件,该事件对应于您处理的具有相同参数的子事件。

    示例

    注意:在 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);
        }
    }
    

    【讨论】:

    • 这看起来完全符合我的需要,但我无法访问控件构造函数中的子项。它无法识别我在 XAML 中附加的名称。
    猜你喜欢
    • 2012-08-18
    • 1970-01-01
    • 1970-01-01
    • 2010-12-28
    • 2015-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-03
    相关资源
    最近更新 更多