简体   繁体   English

将函数绑定到动态创建的元素

[英]Bind function to dynamically created element

Just a quick question. 只是一个简单的问题。 I am working on WPF Project (using c#). 我正在研究WPF项目(使用c#)。

So I Have a function, which on click of a radnom listview item shows it's text in textbox. 所以我有一个函数,点击一个radnom listview项目在文本框中显示它的文本。

private void show_it(object sender, MouseButtonEventArgs e)
    {
        ListViewItem item = (ListViewItem)sender;
        textBox1.Text = item.Content.ToString();

    }

Now, If I create another Listview item in c#, I can't find a way to bind this same function to that newly created element. 现在,如果我在c#中创建另一个Listview项,我找不到将这个相同函数绑定到新创建元素的方法。

        ListViewItem new_i=new ListViewItem();
        new_i.Content = "test";
        /* Tried; not working:
        new_i.SetValue(OnMouseLeftButtonUp, "show_it");
         */
        listView1.Items.Add(new_i);

How can I implement this? 我该如何实现呢? Many thanks in advance. 提前谢谢了。

In XAML register a handler: 在XAML中注册一个处理程序:

<ListView SelectionChanged="ListView_SelectionChanged"> 

In code behind: 代码背后:

private void ListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
  ListView control = (ListView)sender;
  var item = (ListViewItem)control.SelectedItem;
  textBox1.Text = item.Content.ToString();
}

But as HighCore said, DataBinding is the much better solution 但正如HighCore所说,DataBinding是更好的解决方案

Routed event handlers in WPF are programmatically assigned the same way as other .Net events. WPF中的路由事件处理程序以与其他.Net事件相同的方式以编程方式分配。

ListViewItem new_i=new ListViewItem();
new_i.Content = "test";
new_i.Click += show_it;

listView1.Items.Add(new_i);

When you have time, I would recommend that you read up on data binding in WPF. 如果你有时间,我建议你阅读WPF中的数据绑定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM