0

I have a binding in xaml which I would like to delete if some conditions are satisfied at running time. This is a code snippet from my xaml:

 <ComboBox x:Name="cbRad" Width="175"
                HorizontalAlignment="Left"
                cl:FrameworkElementUtil.Required="True"
                Height="18"
                VerticalAlignment="Top"
                TabIndex="20"
                DisplayMemberPath="Isotopo" SelectedValue="{Binding Rad}" RenderTransformOrigin="0.247,7.773"
              Grid.Row ="6"
                Grid.Column="3">
            <ComboBox.SelectedItem>
                <Binding Path="Rad">
                    <Binding.ValidationRules>
                        <v:NotNullValidationRules />
                    </Binding.ValidationRules>
                </Binding>
            </ComboBox.SelectedItem>
        </ComboBox>

I have investigated about BindingOperations.ClearBinding but all the examples are with Textboxes and I don't really get it. Until now I have tried the following:

BindingOperations.ClearBinding(Me.cbRad,ComboBox.SelectedItem)

Which gives me a compilation error, cause ComboBox.SelectedItem is not an adecuate dependency property.

BindingOperations.ClearBinding(Me.cbRad,Me.cbRad.SelectedItem)

This one compiles but it gives a Runtime error because Me.cbRad.Selecteditem is null.

¿How can I remove the binding as if never was declared using code?

Community
  • 1
  • 1
WristMan
  • 337
  • 3
  • 11
  • Have you tried Simply setting the data source to null? – usamazf Mar 29 '16 at 10:42
  • Yes @UsamaZafar , but the NotNullValidation rule used in the xaml does not allow null values. That is the reason I would like to delete the binding, – WristMan Mar 29 '16 at 10:49

1 Answers1

2

Try

BindingOperations.ClearBinding(Me.cbRad, Selector.SelectedItemProperty)

I am guessing your first attempt did not compile because SelectedItem is an instance method and requires an instance in order to use it.

Your second attempt compiled in VB.NET, because SelectedItem returns an Object, and VB.NET (when not in Strict mode) tries to automatically coerce an Object passed into a parameter to the type of the parameter, in this case DependencyPropery.

If SelectedItem would not have been Nothing (let's say an instance of some class), this would also have failed at runtime, because there would be no way to convert that instance into a DependencyProperty.

Since SelectedItem was Nothing, it still failed at runtime, because you can't call ClearBinding without working with some DependencyProperty.

What you actually need is the static field holding the dependency property object -- Selector.SelectedItemProperty.

Zev Spitz
  • 13,950
  • 6
  • 64
  • 136