2012-03-06 21 views
1

動的に作成されたポップアップは、xamlのコンテンツで満たされ、コードの背後にあるコードをバインドする方法が難しいC#コードの背後に作成されます。それが作成されたときに今、それは、XAML内の項目をループし、それぞれに関連付けられたチェックボックスを作成します。動的に作成されたコントロールをコード内で後でバインドする

ListView listView = new ListView(); 

     //Create ListViewItem for each answer 
     foreach (Answer ans in Questions.DataUsedQuestion.AnswerOptions) 
     { 
      ListViewItem item = new ListViewItem(); 
      StackPanel panel = new StackPanel(); 
      CheckBox checkBox = new CheckBox(); 
      TextBlock text = new TextBlock(); 

      panel.Orientation = Orientation.Horizontal; 
      checkBox.Margin = new Thickness(5, 0, 10, 2); 
      text.Text = ans.DisplayValue; 

      panel.Children.Add(checkBox); 
      panel.Children.Add(text); 

      item.Content = panel; 

      listView.Items.Add(item); 
     } 

私は他の場所でこのようなXAMLでバインドされたアプリケーションで同様のコントロールを持っている:

私は背後にあるコードでは、上記と同様のものを達成することができますどのように
<TreeView ItemsSource="{Binding Path=AnswerOptions}" Height="320" Padding="5,5,5,5" Background="Transparent"> 
<TreeView.ItemTemplate > 
    <HierarchicalDataTemplate ItemsSource="{Binding Path=AnswerOptions}" 
           DataType="{x:Type QSB:Answer}" > 
     <StackPanel Orientation="Horizontal" Margin="0,2,0,2"> 

      <CheckBox IsChecked="{Binding Path=IsSelected}" > 
      </CheckBox> 
      <TextBlock Text="{Binding DisplayValue}" Margin="5,0,0,0" /> 
     </StackPanel> 
    </HierarchicalDataTemplate> 
</TreeView.ItemTemplate> 

答えて

4

MSDNの記事How to: Create a Binding in Codeをご覧ください。

Binding binding = new Binding("IsSelected"); 
binding.Source = ans; 
checkBox.SetBinding(CheckBox.IsCheckedProperty, binding); 

binding = new Binding("DisplayValue"); 
binding.Source = ans; 
text.SetBinding(TextBlock.TextProperty, binding); 
+0

ありがとう:

はあなたのような何かを書くことができます!これは私が必要としていたものです。チェックボックスをバインドする必要は実際にはありませんが、それぞれのインスタンスが複数あり、独立して動作する必要があるためです。 – Saggio

関連する問題