Volt
Volt

Reputation: 127

ListBox item template depends on item values

In WPF, MVVC applicaiton I have quite normal listbox:

<ListBox ItemsSource="{Binding Friends}">
</ListBox>

Then each item of list uses following datatemplate:

<DataTemplate DataType="{x:Type model:Friend}">
    <Border BorderThickness="1" BorderBrush="Gray" Padding="3" Name="border" Margin="3">
        <StackPanel Grid.Row="1" Grid.Column="2" Orientation="Horizontal">
            <TextBlock Name="DescriptionDTDataType" Text="{Binding Path=ConnectedUserID}" />
            <TextBlock Name="StatusTitle" Margin="8,0,4,0">Status:</TextBlock>
            <TextBlock Name="Status" Text="{Binding Path=Approved}" />
            <Button Content="Approve" Command="{x:Static inf:Commands.ApproveUserConnection}" CommandParameter="{Binding}"></Button>
            <Button Content="Disapprove" Command="{x:Static inf:Commands.DisapproveUserConnection}" CommandParameter="{Binding}"></Button>
        </StackPanel>
    </Border>
</DataTemplate>

The question is... I want to hide one of the buttons on the basic of Friend.Approved property. For example if Friend.Approved has value "approved" I want to hide button Approved and show only button Dissaprove. On the other hand if Friend.Approved has value "disapproved" then I want opposite. How to achieve this?

Thank you.

Upvotes: 1

Views: 601

Answers (2)

nemesv
nemesv

Reputation: 139758

Beside creating a IValueConverter there is a pure XAML solution using DataTriggers

Just add this to your DataTemplate:

<DataTemplate.Triggers>
    <DataTrigger Binding="{Binding Approved}" Value="approved" >
        <Setter TargetName="Approve" Property="Visibility" Value="Collapsed"/>
    </DataTrigger>
    <DataTrigger Binding="{Binding Approved}" Value="disapproved" >
        <Setter TargetName="Disapprove" Property="Visibility" Value="Collapsed"/>
    </DataTrigger>
</DataTemplate.Triggers>

And name your buttons:

<Button Name="Approve" Content="Approve" ...></Button>
<Button Name="Disapprove" Content="Disapprove" ...></Button>

However if you want to reuse this hiding logic in multiple places in multiple DataTemplates its better to write the Approved text to Visibility converter.

Upvotes: 1

thumbmunkeys
thumbmunkeys

Reputation: 20764

Bind the Buttons Visibility property to Approved and use a value converter to convert Approved to a Visibility value.

Upvotes: 0

Related Questions