2

WPF プロジェクトで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>
4

2 に答える 2

1

いいえ。生のXAMLを使用して、実行時にイベントを保存したり、ロードしたりすることはできません。シリアル化されたXAMLは自己完結型であるため、これはXAMLシリアル化の制限です。つまり、ロードするにはすべてのリソースがraw XAMLである必要があり、イベントのコードロジックはそうではありません。詳細はこちら

于 2011-12-29T17:51:38.987 に答える
1

XamlReader.Load添付eventHandlersすることはできません。したがって、この手法を使用して を動的にアタッチしeventHandlersます。

1- Xaml 文字列をeventHandlers記述せずに - ただし、これらのコントロールの Name プロパティを記述します。

2-文字列をロードしますXamlReader.Load(str);

3- 次に、そこから DataTemplate のコンテンツをロードします。使用してGrid template = ((Grid)(dt.LoadContent()));

注:Gridこれは の親 Control ですDataTemplate

4- イベント ハンドラーをアタッチする名前でコントロールを検索します。 Button img = (Button)template.FindName("MyButtonInDataTemplate");

お役に立てば幸いです。

于 2015-05-01T10:59:21.380 に答える