2

In WPF I'm trying to clear a text box when it is disabled.

At the moment I have the following code:

    <Style TargetType="{x:Type TextBox}"
           BasedOn="{StaticResource stackPanelTextBoxStyle}">
         <Setter Property="Text"
                 Value="{Binding SeatsPlusMinusAdjustmentText, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True, ValidatesOnExceptions=True, NotifyOnValidationError=True}" />
          <Style.Triggers>
              <Trigger Property="TextBox.IsEnabled"
                       Value="false">
                  <Setter Property="Text"
                          Value="{x:Null}" />
              </Trigger>
          </Style.Triggers>
      </Style>

Which does clear the text box just fine, but doesn't set the bound property (SeatsPlusMinusAdjustmentText) to null.

My question is: what do I need to do to get this to set the bound property to null when the text box is cleared? Can this even be done without code-behind even handler?

yu_ominae
  • 2,975
  • 6
  • 39
  • 76
  • Have you made sure the bound property's mode is TwoWay? – D Hansen Jun 08 '16 at 11:40
  • @DHansen `TextBox.Text` binds two-way by default. – Clemens Jun 08 '16 at 11:48
  • 1
    If I remember correctly, Text DP refuses null value and replace it with String.Empty in the Coerce function. Edit: confirmed: http://referencesource.microsoft.com/#PresentationFramework/src/Framework/System/Windows/Controls/TextBlock.cs,2402f71af6e288f2 – nkoniishvt Jun 08 '16 at 11:49
  • @nkoniishvt I'd be happy with `string.Empty`, but at the moment I am not seeing anything coming back to the bound property at all. – yu_ominae Jun 08 '16 at 11:51
  • @DHansen It works fine when I input values manually or when I set it via the property when i instantiate my view model, so two-way seem to be enabled. – yu_ominae Jun 08 '16 at 11:52
  • It's because of the Coerce function, it Coerces the value so you don't get change notification and binding doesn't update I think. Try to set String.Empty in your Trigger and it should work. Check this question: http://stackoverflow.com/questions/3003546/dependency-property-coercion-binding-issues – nkoniishvt Jun 08 '16 at 11:52
  • 3
    This is because when you do `` you override the previous binding. – ZwoRmi Jun 08 '16 at 11:53
  • @ZwoRmi Thanks. That's what I thought was happening. Is there any way to work around that? A different property that I should use maybe? – yu_ominae Jun 08 '16 at 11:57
  • 1
    @nkoniishvt Thanks for the link. I would like to avoid code behind to do this, so I think I'll use a different approach and will clear the bound property in the view model. – yu_ominae Jun 08 '16 at 12:05

0 Answers0