How do I get find my "CheckBox" item that is in the ItemTemplate?

Timothy Khouri picture Timothy Khouri · Mar 2, 2009 · Viewed 15.4k times · Source

I have the following (very simple) ItemsControl:

<ItemsControl Name="BlahList" ItemsSource="{Binding Blah}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <CheckBox Name="MyCheckBox" Content="{Binding Text}" />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

In code, I would like to do the following:

foreach (var dahCurrentItem in BlahList.Items)
{
    var ItemCheckBox = BlahList.GimmeMyControl(dahCurrentItem, "MyCheckBox")

    // I'm going to do something with the check box here...
}

How do I do that?

Answer

Timothy Khouri picture Timothy Khouri · Mar 2, 2009

OK, Kent gets the credit, but it was only mostly right :)

// This part was good:
var container = _itemsControl.ItemContainerGenerator.ContainerFromItem(dahCurrentItem) as FrameworkElement;

but... the second part would return null, so it had to be as follows:

var checkBox = _itemsControl.ItemTemplate.FindName("MyCheckBox", container) as CheckBox;

His code looked like it should have worked, but for my case, I had to do this instead.