Вопрос

I have a ListBox which DataTemplate is TextBox that can be edited. Where should I set Binding TwoWay? In ItemSource or In TextBox binding? Maybe in both? And how it works inside? Is it inherited? So if I set Binding in ItemSource - is it inherited in TextBox?

<ListBox HorizontalAlignment="Left" ItemsSource="{Binding Commands, Mode=TwoWay}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBox Text="{Binding Name}" />
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>
Это было полезно?

Решение 2

Where should I set Binding TwoWay?

You should set this Mode for TextBox like this:

<TextBox Text="{Binding Path=Name, Mode=TwoWay}" />

If I'm not mistaken, the Text property is listed TwoWay mode by default. Therefore, it's construction is not required.

From MSDN:

When used in data-binding scenarios, this property uses the default update behavior of UpdateSourceTrigger.LostFocus.

This means that updates the properties were visible at once, you need to set the property UpdateSourceTrigger to PropertyChanged:

<TextBox Text="{Binding Path=Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />

So if I set Binding in ItemSource - is it inherited in TextBox?

No, inheritance will not be, because settings of Binding unique for each dependency property. Inheritance happens when using DataContext, but again, settings unique for each property.

Другие советы

Two way binding should be setup op your item you need to display, in this case the Textbox. Here you need to have coupling back to your datacontext. You might want to consider setting the UpdateSourceTrigger property to PropertChanged. This way you will always have entered value of your text, even without loosing focus.

The itemsource should not be Two way. One way will do since you probable will be binding to an observable collection. This will only be set once from your datacontext. This will automatically handle the adding and removing of items to your collection.

I'd add your code like this:

<ListBox Margin="10,0,0,0" Width="200" HorizontalAlignment="Left"  ItemsSource="{Binding Commands}" >
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <TextBox Text="{Binding Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top