-->

WPF - set the ItemsSource of List View based on so

2019-09-18 14:48发布

问题:

Is it possible to set the ItemsSource of a list view based on Some condition. I tried the following, but it didn't work.

   <ListView ItemsSource="{Binding FirstTypeOfSource}"  .....>
        <ItemsControl.ItemContainerStyle>
                <Style >
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding Category}" Value="All">
                            <Setter Property="ItemsSource" Value="SecondTypeOfCategory"/>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </ItemsControl.ItemContainerStyle>
   </ListView>

Can someone help to figure out the solution ?

回答1:

Try this

Add a name to a ListView.

<ListView x:Name="someName" ItemsSource="{Binding FirstTypeOfSource}" .....>

Use element name to find desired DependencyProperty:

<DataTrigger Binding="{Binding Category}" Value="All">
    <Setter TargetName="someName" Property="ItemsSource" Value="SecondTypeOfCategory"/>
</DataTrigger>


回答2:

This should do it

    <ListView ItemsSource="{Binding FirstTypeOfSource}">
        <ListView.Style>
            <Style TargetType="ListView">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Category}" Value="All">
                        <Setter Property="ItemsSource" Value="{Binding SecondTypeOfCategory}"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </ListView.Style>
    </ListView>