XamlReader with Click Event

▼魔方 西西 提交于 2021-02-07 10:44:55

问题


I am using XamlReader in my WPF project. And it works (My reference)

My current sample Xaml is like that:

<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>

and adding button's click event like this:

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

Is it possible to write xaml like this?

<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>

回答1:


XamlReader.Load not allowed to attach eventHandlers in it. so use this technique to dynamically attach the eventHandlers to it.

1- Write your Xaml string without eventHandlers -But write the Name property of those Controls.

2- Load the string with XamlReader.Load(str);

3- Then load the content of DataTemplate from it. using Grid template = ((Grid)(dt.LoadContent()));

Note: here Grid is the parent Control in DataTemplate.

4- Find the Control by Name you want to attach the Event Handler. Button img = (Button)template.FindName("MyButtonInDataTemplate");

I hope it helps.




回答2:


No. You can't save events or load them at run-time using raw XAML. It's a limitation of XAML Serialization, as serialized XAML is self-contained, means every resource should be in raw XAML to load and event's code logic is not . Read more here



来源:https://stackoverflow.com/questions/8666522/xamlreader-with-click-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!