gpt4 book ai didi

c# - 如何从用户控件引发自定义路由事件?

转载 作者:可可西里 更新时间:2023-11-01 08:59:35 28 4
gpt4 key购买 nike

在我的用户控件中,我有一个按钮,单击该按钮会引发自定义路由事件。我试图引发它,但它没有在 MainWindow.xaml 中触发。

UserControl 中按钮的 Xaml:

<Button x:Name="PART_Add" Content="+" Grid.Column="3" Margin="0,0,0,0" Style="{DynamicResource dTranspButton}" Click="btnAdd_Click"/>

用户控件 C# 代码:

//AddClick Event

public static readonly RoutedEvent AddClickEvent = EventManager.RegisterRoutedEvent("AddClick", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(dCB_Props));

public event RoutedEventHandler AddClick
{
add { AddHandler(AddClickEvent, value); }
remove { RemoveHandler(AddClickEvent, value); }
}

void RaiseAddClickEvent()
{
RoutedEventArgs newEventArgs = new RoutedEventArgs(dCB_Props.AddClickEvent);
}

protected void OnAddClick()
{
RaiseAddClickEvent();
}

//objects events

private void btnAdd_Click(object sender, System.Windows.RoutedEventArgs e)
{
RaiseAddClickEvent();
}

MainWindow.xaml 中 UserControl 实例的 Xaml 代码:

<local:dCB_Props x:Name="cb1" Margin="41.166,0,36.19,25" VerticalAlignment="Bottom" Height="30" Width="141" AddClick="dCB_Props_AddClick">
<local:dCB_Props.Items>
<ComboBoxItem Content="item1"/>
</local:dCB_Props.Items>
</local:dCB_Props>

应在 MainWindow.xaml.cs 中触发的 C# 代码:

private void dCB_Props_AddClick(object sender, System.Windows.RoutedEventArgs e)
{
MessageBox.Show("This Works");
}

最佳答案

你需要打电话

RaiseEvent(new RoutedEventArgs(AddClickEvent));

关于c# - 如何从用户控件引发自定义路由事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10144826/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com