将 UserControl 中的事件绑定到父级 Window- 路由事件 - C# XAML
Bind an event from a UserControl into the parent Window- Routed events - C# XAML
我在堆栈面板中有多个相同用户控件的实例,每个用户控件中都有一个按钮。
当我单击此按钮时,我希望它打开一个新的 window,然后禁用包含所有用户控件的堆栈面板,这样就无法打开此 window 的多个实例同一时间。然后我希望能够在用户关闭新打开的 window 时重新启用堆栈面板。
目前我有这段代码,当我的按钮位于主 Window XAML 而不是用户控件的一部分时:
private void ButtonClick(object sender, RoutedEventArgs e)
{
RouteViewer Rv = new RouteViewer((sender as Button).Tag).ToString());
Rv.Owner = this;
Rv.Show();
StackPanel.IsEnabled = false; //Disables the stackpanel
Rv.Closed += new EventHandler(RvClosed);
}
void RvClosed(object sender, EventArgs e)
{
StackPanel.IsEnabled = true; //Re-enables the stackpanel
}
如您所见,问题是由于堆栈面板不属于用户控件。我一直在谷歌搜索并怀疑答案与路由事件有关,我们将不胜感激。
看看这个网站 here,你会想使用事件 "Bubbling"。
代码可能如下所示:
C# 在用户控件中:
private void ButtonClick(object sender, RoutedEventArgs e)
{
RouteViewer Rv = new RouteViewer(((sender as Button).Tag).ToString());
Rv.Show();
var newEventArgs = new RoutedEventArgs(RvOpenedEvent);
RaiseEvent(newEventArgs);
}
public static readonly RoutedEvent RvOpenedEvent = EventManager.RegisterRoutedEvent(
"RvOpened",
RoutingStrategy.Bubble,
typeof(RoutedEventHandler),
typeof(ClassName));
public event RoutedEventHandler RvOpened
{
add { AddHandler(RvOpenedEvent, value); }
remove { RemoveHandler(RvOpenedEvent, value); }
}
然后在 Main Window XMAL :
<UserControl:Name RvOpened="RouteViewerOpened"/>
然后在 Main Window C#:
private void RouteViewerOpened(object sender, RoutedEventArgs e)
{
ServiceStack.IsEnabled = false;
e.Handled = true;
}
我在堆栈面板中有多个相同用户控件的实例,每个用户控件中都有一个按钮。
当我单击此按钮时,我希望它打开一个新的 window,然后禁用包含所有用户控件的堆栈面板,这样就无法打开此 window 的多个实例同一时间。然后我希望能够在用户关闭新打开的 window 时重新启用堆栈面板。
目前我有这段代码,当我的按钮位于主 Window XAML 而不是用户控件的一部分时:
private void ButtonClick(object sender, RoutedEventArgs e)
{
RouteViewer Rv = new RouteViewer((sender as Button).Tag).ToString());
Rv.Owner = this;
Rv.Show();
StackPanel.IsEnabled = false; //Disables the stackpanel
Rv.Closed += new EventHandler(RvClosed);
}
void RvClosed(object sender, EventArgs e)
{
StackPanel.IsEnabled = true; //Re-enables the stackpanel
}
如您所见,问题是由于堆栈面板不属于用户控件。我一直在谷歌搜索并怀疑答案与路由事件有关,我们将不胜感激。
看看这个网站 here,你会想使用事件 "Bubbling"。
代码可能如下所示: C# 在用户控件中:
private void ButtonClick(object sender, RoutedEventArgs e)
{
RouteViewer Rv = new RouteViewer(((sender as Button).Tag).ToString());
Rv.Show();
var newEventArgs = new RoutedEventArgs(RvOpenedEvent);
RaiseEvent(newEventArgs);
}
public static readonly RoutedEvent RvOpenedEvent = EventManager.RegisterRoutedEvent(
"RvOpened",
RoutingStrategy.Bubble,
typeof(RoutedEventHandler),
typeof(ClassName));
public event RoutedEventHandler RvOpened
{
add { AddHandler(RvOpenedEvent, value); }
remove { RemoveHandler(RvOpenedEvent, value); }
}
然后在 Main Window XMAL :
<UserControl:Name RvOpened="RouteViewerOpened"/>
然后在 Main Window C#:
private void RouteViewerOpened(object sender, RoutedEventArgs e)
{
ServiceStack.IsEnabled = false;
e.Handled = true;
}