【问题标题】:Binding dynamically created control in code behind在后面的代码中绑定动态创建的控件
【发布时间】:2012-03-06 18:49:01
【问题描述】:

我已经动态创建了在运行时在 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>

我怎样才能在后面的代码中完成与上面类似的事情?

【问题讨论】:

    标签: c# wpf data-binding


    【解决方案1】:

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

    【讨论】:

    • 谢谢!这正是我所需要的,除了我实际上不需要绑定复选框,因为每个复选框可以有多个实例,并且需要它们独立运行。
    猜你喜欢
    • 2016-06-24
    • 1970-01-01
    • 1970-01-01
    • 2011-05-19
    • 1970-01-01
    • 2018-06-26
    • 2023-03-09
    • 2016-02-22
    • 1970-01-01
    相关资源
    最近更新 更多