denny
denny

Reputation: 345

Binding DataTemplate controls in DataGridTemplateColumn

I have bounded DataGrid where Items are ObservableCollection of pairs {Prop1, Prop2}

<DataGrid ItemsSource="{Binding Items}" AutoGenerateColumns="False">
                   <DataGrid.Columns>
                        <DataGridTemplateColumn>
                            <DataGridTemplateColumn.CellTemplate>
                                <DataTemplate>
                                    <TextBox >
                                        <TextBox.Text>
                                            <Binding Path="Prop1">
                                            </Binding>
                                        </TextBox.Text>   
                                    </TextBox>
                                </DataTemplate>
                            </DataGridTemplateColumn.CellTemplate>
                        </DataGridTemplateColumn>

How to bind TextBox Text property to Prop1? I tried as shown above but its not working (looks like data context of TextBox is set to main window).

Upvotes: 0

Views: 802

Answers (1)

Grx70
Grx70

Reputation: 10349

I've managed to reproduce the issue in question (I assume that "it's not working" means that the value entered in the TextBox is not pushed to your view-model). I am not sure about the exact reasons, but it seems that in this particular scenario, if you don't explicitly set Binding.UpdateSourceTrigger, it defaults (or at least acts like it) to UpdateSourceTrigger.Explicit. So the solution to this problem is to explicitly set the UpdateSourceTrigger on the binding to either UpdateSourceTrigger.LostFocus or UpdateSourceTrigger.PropertyChanged:

<DataGrid ItemsSource="{Binding Items}" AutoGenerateColumns="False">
    <DataGrid.Columns>
        <DataGridTemplateColumn>
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBox Text="{Binding Prop1, UpdateSourceTrigger=LostFocus}" />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

Upvotes: 1

Related Questions