2011-04-27 29 views
1

我有都有一個複選框和網頁瀏覽器中的子控件:WPF - 家長如何知道子控件複選框的「選中」事件?

<UserControl x:Class="Some.MyUserControl" etc.> 
    <Grid> 
    <CheckBox x:Name="chkA" Content="Analysis" Checked="chkA_Checked"></CheckBox> 
    <WebBrowser Margin="0,30,0,0" Name="wbA"></WebBrowser> 
    </Grid> 
</UserControl> 

我把我的MainWindow.xaml /的.cs這種控制:

<Window x:Class Some.MainWindow xmlns:local="clr-namespace:Some" etc.> 
    <Grid> 
    <local:MyUserControl x:Name="MyUserControl_Main"></local:MyUserControl> 
    </Grid> 
</Window> 

我的問題是我的主窗口怎樣才能知道CheckBox(chkA)是否已被選中?到目前爲止,只有實際的用戶控件知道它已被點擊?我怎麼能暴露我的MainWindow的「檢查」事件看到?或者,還有更好的方法?

我搜索了網頁,但似乎無法將我的頭圍繞我所看到的。

謝謝你在前進,

-newb

編輯1:

我想,沒有運氣以下,但可能是在正確的軌道上。

在我的MainWindow.xaml.cs我已經加入:

public static readonly RoutedEvent CheckedEvent = EventManager.RegisterRoutedEvent("Checked", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(MyUserControl)); 

public event RoutedEventHandler Checked 
{ 
    add { AddHandler(CheckedEvent, value); } 
    remove { RemoveHandler(CheckedEvent, value); } 
} 

而且我已經加入MyUserControl.xaml.cs內:

private void chkA_Checked(object sender, RoutedEventArgs e) 
{ 
    RoutedEventArgs args = new RoutedEventArgs(MainWindow.CheckedEvent); 
    RaiseEvent(args); 
} 

編輯2:

感動前面提到的代碼放入MyUserControl.xaml.cs中:

public static readonly RoutedEvent CheckedEvent = EventManager.RegisterRoutedEvent("Checked", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(MyUserControl)); 

public event RoutedEventHandler Checked 
{ 
    add { AddHandler(CheckedEvent, value); } 
    remove { RemoveHandler(CheckedEvent, value); } 
} 

private void chkA_Checked(object sender, RoutedEventArgs e) 
{ 
    RoutedEventArgs args = new RoutedEventArgs(MainWindow.CheckedEvent); 
    RaiseEvent(args); 
} 

現在我能看到「檢查」事件「泡沫」起來像這樣:

<Window x:Class Some.MainWindow xmlns:local="clr-namespace:Some" etc.> 
    <Grid>  
    <local:MyUserControl x:Name="MyUserControl_Main" **Checked="MyUserControl_Main_Checked"**></local:MyUserControl> 
    </Grid> 
</Window> 

感謝@馬特的小費!

編輯3:

馬特的第一個答案是最好的方式,我是有「複選框」與「複選框」 ...添加CheckBox.Checked到電網捕獲事件:

回答

1

Checked事件冒泡給父母並在那裏抓住它。這是路由事件的美麗!

<Grid CheckBox.Checked="CheckBox_Checked"> 
    <local:MyUserControl x:Name="MyUserControl_Main" /> 
</Grid> 
+0

我還沒有機會測試這個,但我99%肯定它會工作,即使CheckBoxes在UserControl中。當然,如果它們在DataTemplate中,它就可以工作。 – 2011-04-27 21:20:13

+0

@馬特漢密爾頓 感謝您的回覆,我已經編輯了我的問題與額外的信息,因爲我更加關注路由事件。 – Mike 2011-04-27 22:07:02

+0

@Mike - 你不需要任何額外的代碼。根據我的回答,所有你需要處理CheckBox.Checked在某個地方的「主機」窗口中,你的UserControl中的任何Checked事件都會冒泡到那裏。 – 2011-04-27 22:25:35

0

你在正確的軌道上,但你應該在MyUserControl聲明路由事件,而不是在MainWindow ...它是引發事件,而不是窗口的用戶控件。你這樣做的方式,你的控制明確取決於MainWindow,這是不好的做法,沒有必要。

相關問題