Reputation: 1732
I want to do this in XAML with a trigger, how do I do it?
If ListBox1.SelectedIndex > -1 Then
Border1.Visibility = Windows.Visibility.Visible
Else
Border1.Visibility = Windows.Visibility.Hidden
End If
This XAML code does NOT work. SelectedIndex
member is not valid because it does not have a qualifying type name.
<ListBox.Triggers>
<Trigger SourceName="ListBox1" Property="SelectedIndex" Value="False">
<Setter TargetName="Border1" Property="Visibilty" Value="Hidden" />
</Trigger>
</ListBox.Triggers>
Upvotes: 2
Views: 8649
Reputation: 62919
It is as simple as this:
<Border x:Name="Border1" ... Visibility="Visible" ... />
...
<Trigger SourceName="ListBox1" Property="ListBox.SelectedIndex" Value="-1">
<Setter TargetName="Border1" Property="UIElement.Visibilty" Value="Hidden" />
</Trigger>
Update
I see from the new code you posted that you're trying to use a trigger directly on the ListBox. The trigger must be in a ControlTemplate to use SourceName. If your UI is done with "custom controls" (my preference), you will already have a ControlTemplate to put it in. If not, you can easily add one by wrapping your XAML in a generic "ContentControl" (base class, not any subclass) and setting its template, like this:
<Window ...>
...
<ContentControl>
<ContentControl.Template>
<ControlTemplate TargetType="{x:Type ContentControl}">
<Grid>
...
<ListBox x:Name="ListBox1" ... />
...
<Border x:Name="Border1">
...
</Border>
</Grid>
<ControlTemplate.Triggers>
<Trigger SourceName="ListBox1" Property="ListBox.SelectedIndex" Value="-1">
<Setter TargetName="Border1" Property="UIElement.Visibility" Value="Hidden" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</ContentControl.Template>
</ContentControl>
...
</Window>
A better solution would probably be to use custom controls. Using a binding with a converter is possible but not as elegant IMHO.
Upvotes: 4
Reputation: 17669
Can you show me how are you trying to do this in xaml?
In case of this error message you need to mention type name also with the property inside trigger.
<Trigger SourceName="ListBox1" Property="ComboBox.SelectedIndex" Value="-1">
<Setter TargetName="Border1" Property="Border.Visibility" Value="Hidden" />
</Trigger>
Further, it seems that you are adding a Trigger in <ListBox.Triggers>
collection, but you can only add EventTrigger in to this collection. So you need to declate a Style for your ListBox to add a Trigger for that and your Border element should be inside the ControlTemplate of ListBox, but in your case Border seems to be outside of ListBox, so declaring a style will not be a solution. Instead you should use Binding with SelectIndex property with the help of a ValueConverter(say IndexToVisibilityConverter). You need to define this converter in codebehind and add it in resources.
<Border Visibility={Binding Path=SelectedIndex, ElementName=ListBox1, Converter={StaticResource IndexToVisibilityConverter}}/>
Choice is totally on your requirements.
Upvotes: 6