开发者

Binding ListView Visibility when DataContext is a CollectionViewSource

I'm new to the world of WPF and I am constantly asking myself 'am I doing this right?'. My current scenario involves binding the Visibility of a ListView based on the state of a collection. I have the Converter worked out fine, my issue/question is how to best declare the XAML to setup the binding.

First off, I have a CollectionViewSource, which is bound to an ObservableCollection of View Models:

<CollectionViewSource x:Key="MyViewSource" Source="{Binding Path=MyCollection}" />

Next, I have declared my ListView as follows:

<ListView DataContext="{StaticResource MyViewSource}" ItemsSource="{Binding}" />

The code for my Converter:

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    if (value != null && (value is ICollection && (value as ICollection).Count > 0))
         开发者_如何学C   return Visibility.Visible;

    return Visibility.Hidden;
}

I've come up with two ways to setup the binding so that it actually works:

The first:

Visibility="{Binding Path=SourceCollection, 
  Converter={StaticResource ListToVisibilityConverter}}"

The second:

Visibility="{Binding RelativeSource={RelativeSource Self},
  Path=DataContext.Source,
  Converter={StaticResource ListToVisibilityConverter}}"

In the second scenario, the Convert method is called twice, and I'm not sure why... This leads me to believe that this is not the 'right' way.

Lastly, I also tried setting the path as Path=Source and Path=DataContext.Source but those fail with these errors at runtime (respectively):

BindingExpression path error: 'DataContext' property not found on 'object' ''ListCollectionView' BindingExpression path error: 'Source' property not found on 'object' ''ListCollectionView'

I was under the impression that when I set the DataContext of the ListView to be a CollectionViewSource, I should be able to access its properties (e.g. Source). Why am I required to add the RelativeSource here?

There are a series of sub-questions in here and I fully realize that. As such, answering just a few or giving some pointers is greatly appreciated.

Thanks!


If you want to bind to certain properties on objects which provide items you need to set BindsDirectlyToSource to true in the binding.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜