2011-12-29 50 views
0

我在我的WPF項目中使用XamlReader。和它的作品(My reference帶點擊事件的XamlReader

我現在的樣本XAML是這樣的:

<Grid xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" Width="800" Height="600"> 
    <Button Name="Test1" Content="Test1" Width="357" Height="88" Margin="14,417,0,0" ></Button> 
    <Button Name="Test2" Content="Test2" Width="357" Height="88" Margin="14,529,0,0" ></Button> 
</Grid> 

和添加按鈕的單擊事件是這樣的:

button = LogicalTreeHelper.FindLogicalNode(rootObject, "Test1") as Button ; 
button.Click += new RoutedEventHandler(Button1_Click); 

是否可以寫XAML這樣嗎?

<Grid xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" Width="800" Height="600"> 
    <Button Name="Test1" Content="Test1" ... Click="Button1_Click"></Button> 
    <Button Name="Test2" Content="Test2" ... Click="Button2_Click"></Button> 
</Grid> 

回答

0

XamlReader.Load不允許附加eventHandlers在裏面。所以使用這種技術來動態附加eventHandlers

1-編寫您的Xaml字符串而不使用eventHandlers - 寫入這些控件的Name屬性。

2-負荷與XamlReader.Load(str);

3-字符串然後從它加載的DataTemplate的內容。使用Grid template = ((Grid)(dt.LoadContent()));

注意:這裏GridDataTemplate中的父控件。

4-按名稱查找要附加事件處理程序的控件。 Button img = (Button)template.FindName("MyButtonInDataTemplate");

我希望它有幫助。

0

不能。您不能使用原始XAML在運行時保存事件或加載它們。這是XAML序列化的限制,因爲序列化的XAML是獨立的,意味着每個資源都應該在原始XAML中加載,而事件的代碼邏輯則不是。閱讀全文here

+0

謝謝Neeraj。我想,我也不能添加_Template_屬性。 – makcura 2011-12-30 09:57:14