在ItemsControl子项

时间:2015-08-11 14:22:33

标签: wpf itemscontrol

我有ItemsControl绑定到ObservableCollection。如果用户双击其中一个项目,我想访问绑定到它的数据,以便我可以编辑它。问题是,由于DataBinding自动生成Items,我怎么能在它们上注册事件?

为了让事情更加清晰,这里有一个简单的例子:

包含源列表的类:

public class SourceClass
{
    public SourceClass()
    {
        ListOfItems = new ObservableCollection<string>();
    }

    public ObservableCollection<string> ListOfItems
    {
        get;
        set;
    }
}

XAML:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Loaded="Window_Loaded"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <ItemsControl x:Name="itemsControl">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding}" />
                    </DataTemplate >
            </ItemsControl.ItemTemplate>
        </ItemsControl> 
    </Grid>
</Window>

绑定代码:

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    SourceClass source = new SourceClass();
    source.ListOfItems.Add("Item 1");
    source.ListOfItems.Add("Item 2");
    source.ListOfItems.Add("Item 3");
    source.ListOfItems.Add("Item 4");
    source.ListOfItems.Add("Item 5");

    itemsControl.ItemsSource = source.ListOfItems;
}

0 个答案:

没有答案