簡體   English   中英

在后面的代碼中綁定動態創建的控件

[英]Binding dynamically created control in code behind

我已經動態創建了彈出窗口,這些彈出窗口是在運行時在C#代碼后面創建的,其中填充了來自xaml的內容,並且難以在后面的代碼中綁定它們。 現在,當它被創建時,它會循環遍歷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>

如何在后面的代碼中完成類似於上面的內容?

請查看MSDN文章如何:在代碼中創建綁定

你可以這樣寫:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM