How to change CollectionView.Source binding?

I originally had this code in XAML:

<CollectionViewSource x:Name="cSource">
  <CollectionViewSource.Source>
    <Binding Source="{StaticResource NameOfXmlDataProvider}" XPath="letter"/>
  </CollectionViewSource.Source>
<CollectionViewSource>

But I wanted to save the binding object in C # code in order to be able to dynamically change its xpath. I currently have this code:

CollectionViewSource viewSource = this.FindResource("cSource") as CollectionViewSource;
Binding binding = new Binding( "Source" );
binding.Source = _xmlDataProvider;
binding.XPath = "/new/path/to/nodes";
BindingOperations.SetBinding( viewSource, CollectionViewSource.SourceProperty, binding );

This compiles and does not complain, but when called, it only results in empty lists. I cannot find similar examples on the Internet - most of them concern data providers, but I want to change the binding.

  • Does anyone know how to fix this?
  • Or is there a better way to do this?
  • Perhaps retrieving the binding object from the collection and changing it?
+1
source share
3 answers

XAML (yuk) (yukkier), , .

<CollectionViewSource x:Name="cSource">
  <CollectionViewSource.Source>
    <Binding Source="{Binding MyDataProviderProperty}" XPath="{Binding MyDataXPathProperty}"/>
  </CollectionViewSource.Source>
<CollectionViewSource>

MVVM, , DataContext , UserControl ElementName datacontext ( , DataContext UserControl ( , , ):

<UserControl x:Class="BindingTests.BindingToSelfExample"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400" x:Name="MyViewClass">
    <Grid x:Name="LayoutRoot" Background="White" DataContext="{Binding ElementName=MyViewClass}">
        <TextBlock Text="{Binding SomePropertyOfTheCodeBehind}" Width="100" Height="20"/>
    </Grid>
</UserControl>

, MyDataProviderProperty MyDataXPath, .

+2

collView SetBinding(). - collView.SetBinding(CollectionViewSource.SourceProperty, binding)

http://msdn.microsoft.com/en-us/library/ms752347.aspx .

0

The problem with the question code is the Sourcebinding. So what works:

 Binding binding = new Binding();

If the constructor is used with a parameter, the parameter is set as Pathbindings. Then (further) XPathbindings are used from this path. So he tried to find the "Source" in XML, which would result in an empty selection. Then xpath worked on an empty set of nodes.

Thus, you can use the bindings from the code.

0
source

All Articles