views:

24

answers:

1

What is wrong with this code ? It throws the Exception: "View cannot be shared by more than one ListView"

<ListView 
    ItemsSource="{Binding}"  
    SelectionMode="Extended">
 <ListView.Style>

  <Style TargetType="ListView">   
   <Style.Triggers>
    <DataTrigger Binding="{Binding ElementName=MyControl, Path=IsCompany}" Value="True">
     <Setter Property="View" Value="{StaticResource GridViewCompanies}" />
    </DataTrigger>
    <DataTrigger Binding="{Binding ElementName=MyControl, Path=IsCompany}" Value="False">
     <Setter Property="View" Value="{StaticResource GridViewPeople}" />
    </DataTrigger>
    <DataTrigger Binding="{Binding ElementName=MyControl, Path=IsCompany}" Value="{x:Null}">
     <Setter Property="View" Value="{StaticResource GridViewBoth}" />
    </DataTrigger>
   </Style.Triggers>
  </Style>

 </ListView.Style>          
</ListView>

public bool? IsCompany
{
 get { return (bool?)GetValue(IsCompanyProperty); }
 set { SetValue(IsCompanyProperty, value); }
}        
public static readonly DependencyProperty IsCompanyProperty =
 DependencyProperty.Register("IsCompany", typeof(bool?), typeof(MyControl), new UIPropertyMetadata(null));

EDITED:

I've tried to set the View in code behind and it works. What's the problem with XAML then?

if() ..
MyListView.View = Resources["GridViewCompanies"] as GridView;
A: 

The error is because the GridView is being applied to more than one ListView. Is your ListView Style being applied to more than one control? I took a look in Reflector, and it looks like this scenario should work for a single control.

What exactly are you trying to accomplish? I imagine you just want to show different columns. Maybe you can create an attached behavior to generate columns for the GridView depending on the value of the property you are binding to.

Abe Heidebrecht
No I only got 1 ListView in which I have directly defined the Style. All the StaticResources (GridViewBoth, ...) are defined in the UserControl's Resources.Yes you're right, that's exactly what I want to do - show different columns based on the property.
PaN1C_Showt1Me