Robby Smet
Robby Smet

Reputation: 4661

Bind boolean to visualstate

I'm working with expression blend and I want to change the state of a textbox to a red border and red text when a listbox has no elements.

So when the text changes I filter the listbox.

private void OnIPAddressTextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
{
   compositeViewModel.manualServerInfoViewModel.FilterServers(IPAddressTextbox.Text);
}

In my viewmodel I filter the results and check if there are any results. Then I set the boolean property accordingly

public bool HasResults { get; set; }

public void FilterServers(string FilterCriteria)
{
    ....
    HasResults = (FilteredManualServers.Count > 0)? true : false;
}

In my xaml I try to change to State of the textbox to the visualstate with the red border when the HasResults boolean is false.

<TextBox x:Name="IPAddressTextbox" Height="27.24" Margin="-92.799,8,0,0" VerticalAlignment="Top" Width="209" Background="#FFF3F3F3" BorderBrush="#FF2F2F2F" TextChanged="OnIPAddressTextChanged" >
     <i:Interaction.Behaviors>
          <ei:DataStateBehavior Binding="{Binding HasResults}"  TrueState="NoResults" />
      </i:Interaction.Behaviors>
</TextBox>

And this is the NoResult visualstate

<VisualStateGroup x:Name="Filtering">
    <VisualState x:Name="NoResults">
        <Storyboard>
            <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Border.BorderBrush).(SolidColorBrush.Color)" Storyboard.TargetName="IPAddressTextbox">
                        <EasingColorKeyFrame KeyTime="0" Value="Red"/>
            </ColorAnimationUsingKeyFrames>
            <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(TextElement.Foreground).(SolidColorBrush.Color)" Storyboard.TargetName="IPAddressTextbox">
                        <EasingColorKeyFrame KeyTime="0" Value="#FFCE1010"/>
            </ColorAnimationUsingKeyFrames>
        </Storyboard>
    </VisualState>
</VisualStateGroup>

But when the number of items is empty and the boolean is false, nothing happens.

What am I doing wrong?

Upvotes: 3

Views: 494

Answers (1)

Torben Schramme
Torben Schramme

Reputation: 2140

The problem is that the UI doesn't know when the value of HasResults changes. There is no polling mechanism in bindings. You have to inform the UI about changes for HasResults. You have two possibilities.

  1. Convert the HasResults property to a dependency property when your view model inherits from DependencyObject. More information about dependency properties:

  2. Implement the INotifyPropertyChanged interface in your view model and raise the PropertyChanged event in the setter of HasResults

Upvotes: 2

Related Questions