views:

24

answers:

1

Hi!

I try to implement PrepareContainerForItemOverride method of ItemsControl. It will put items to TextBox. It works nice, but how can I binding an item to the textbox text property? One way mode works nice, but when I want two way mode, I have to know the path.

Here is my code:

protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
        {
            base.PrepareContainerForItemOverride(element, item);

            if (element is TextBox)
            {
                //((TextBox)element).Text = (string)item;
                Binding binding = new Binding("I don't know what should i write here.");
                binding.Mode = BindingMode.TwoWay;
                ((TextBox)element).SetBinding(TextBox.TextProperty, binding);
            }
}

Thank you for your help!

A: 

If the commented line in the code in your question is what you have before then it indicates that the type of item you are providing is String. Two way binding on a string makes no sense the binding would not know where to assign the new value.

The type of items being displayed would need to be some object that has a property of type String, it would be the name of this proprerty that you pass to the Binding constructor.

That said its not clear why you would even need to sub-class ItemsControl in this way. Why not:-

<ItemsControl ItemSource="{Binding SomeEnumberableOfObjectsThatHaveASomeStringProperty}">
  <ItemsControl.ItemTemplate>
    <DataTemplate>
       <TextBox Test="{Binding SomeString, Mode=TwoWay}" />
    </DataTemplate>
  </ItemsControl.ItemTemplate>
</ItemsControl>
AnthonyWJones