我有一个带按钮和用户控件的窗口。现在,当我点击按钮,引发事件时,我想抓住用户控件。我猜这个原理叫做事件隧道。但我也不知道,如果这种方式是捕捉按钮点击事件的正确方法。
实施例
<Window x:Class="EventTunneling.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:uc="clr-namespace:EventTunneling"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="30"></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
</Grid.RowDefinitions>
<Button Grid.Row="0" Content="Click me"></Button>
<uc:Control Grid.Row="1"></uc:Control>
</Grid>
</Window>
用户控件
<UserControl x:Class="EventTunneling.Control"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
</Grid>
</UserControl>
现在我想在主窗口中引发的usercontrol的部分类上捕获事件。我怎么能这样做?
namespace EventTunneling
{
/// <summary>
/// Interaction logic for Control.xaml
/// </summary>
public partial class Control : UserControl
{
public Control()
{
InitializeComponent();
}
}
}
答案 0 :(得分:1)
不幸的是,您执行所有错误。首先,您需要将集合的数据从后面的代码绑定到DataGrid.ItemsSource
属性。然后,当点击Button
时,只需在后面的代码中处理它,您可以访问该集合并根据需要保存它:
在UserControl
:
<DataGrid ItemsSource="{Binding Items}" ... />
在MainWindow
:
<Button Grid.Row="0" Content="Click me" Click="Button_Click" />
在后面的代码中(你应该在这个属性上实现INotifyPropertyChanged
接口):
public ObservableCollection<YourDataType> Items { get; set; }
...
private void Button_Click(object sender, RoutedEventArgs e)
{
SaveAsXml(Items);
}
在构造函数后面的代码中(或者以你喜欢的任何有效方式设置它):
DataContext = this;
答案 1 :(得分:0)
答案 2 :(得分:0)
您可以在单击按钮时执行此操作,在用户Control中调用公共方法:
namespace EventTunneling
{
public partial class Control : UserControl
{
public Control()
{
InitializeComponent();
}
public void CatchEventOnUserControl()
{
//do your job here
//....
}
}
}
然后单击该按钮时,调用CatchEventOnUserControl方法
<Window x:Class="EventTunneling.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:uc="clr-namespace:EventTunneling"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="30"></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
</Grid.RowDefinitions>
<Button Grid.Row="0" Content="Click me" Click="Button_Click"></Button>
<uc:Control x:Name="mycontrol" Grid.Row="1"></uc:Control>
</Grid>
而后面的代码是
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
mycontrol.CatchEventOnUserControl();
}
}