views:

1050

answers:

2

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?

+3  A: 

Firstly, don't if there's any way you can avoid it. It's much cleaner to bind the various properties of the CheckBox to your view model rather than trying to pull them out manually.

That said, if you need to get to your CheckBox, you can should be able to use code like this:

var container = _itemsControl.ItemContainerGenerator.ContainerFromItem(dahCurrentItem) as FrameworkElement;
var checkBox = container.FindName("MyCheckBox") as CheckBox;

HTH, Kent

Kent Boogaart
You sir, are beautiful! - I agree with your statement, but in this case I'm doing a "Check All" and "Check None" type function... I realize I could have the "isChecked" bound to some array, and then re-update bindings... but just foreaching and checking is lazier... I mean.. easier :) Thanks again!
Timothy Khouri
OK, I had to take away the "answered" check box... because I'm only getting "NULL". I imagine this is really close, but there must be something small missing.
Timothy Khouri
+3  A: 

OK, Kent get's 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.

Timothy Khouri
+1 for fixing my bug ;)
Kent Boogaart