Search code examples
wpfxamlxaml-binding

Binding Mode based on some condition WPF


I am trying to Set binding mode base on some condition. For example I want to set the binding mode to be "OneWayToSource" when adding data but "TwoWay" when updating data using the same XAML File. In short I don't want to show data when in add mode but want to show it when it is in update mode.

 <DataGridTemplateColumn Header="Selling Price" Width="Auto" KeyboardNavigation.IsTabStop="False" IsReadOnly="True" MinWidth="120">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <gc:CTextBox Text="{Binding Path=SellingPrice,Mode=OneWayToSource,UpdateSourceTrigger=PropertyChanged,StringFormat=N2}"  VerticalAlignment="Center" HorizontalAlignment="Center" Style="{DynamicResource TextBoxesCustomStyle}" MinWidth="130" TextWrapping="NoWrap"  IsEnabled="{Binding IsNew}"/>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>

Here is my XAML. I have tried different ways and have searched internet but didn't get lucky to work around this.


Solution

  • You can use CellTemplate for showing the data, and use a different DataTemplate inside CellEditingTemplate when your cell is in Edit Mode.

    There is a nice example for it in MSDN: https://msdn.microsoft.com/en-us/library/system.windows.controls.datagridtemplatecolumn.celleditingtemplate(v=vs.110).aspx