1

最初我在 XAML 中有这段代码:

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

但我想在 C# 代码中保留一个绑定对象,以便能够动态更改它的 xpath。目前我有这个代码:

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 );

这会编译并且不会抱怨,但是当被调用时它只会导致一个空列表。我似乎无法在网络上找到相关的示例——它们中的大多数都与数据提供者打交道,但我想更改绑定。

  • 有人知道如何解决这个问题吗?
  • 还是有更好的方法来做到这一点?
  • 也许从collectionview中检索绑定对象并更改它?
4

4 回答 4

2

与其绑定到 XAML 中的静态资源 (yuk) 或动态更改绑定 (yukkier),不如绑定到您可以更改的内容。

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

如果您不想使用完整的 MVVM,一个不错的技巧是您可以通过简单地命名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 的代码中具有通知属性,您就可以将它们更改为您喜欢的内容。

于 2011-06-24T14:16:17.053 回答
0

您需要使用SetBinding()collView 的方法。应该是这样的collView.SetBinding(CollectionViewSource.SourceProperty, binding)

查看http://msdn.microsoft.com/en-us/library/ms752347.aspx以获取更多参考。

于 2011-06-22T15:33:54.560 回答
0

问题中的代码问题在于Source绑定。所以有效的是:

 Binding binding = new Binding();

如果 Constructor 与参数一起使用,则参数设置为Path绑定的。然后从该路径使用绑定的(附加)XPath。所以它试图在导致空选择的 XML 中找到“源”。xpath 然后在一组空节点上工作。

因此可以使用代码中的绑定。

于 2011-06-27T10:14:32.277 回答
0

试试这个:

ICollectionView cSource {get;set;}

在构造函数中:

cSource = new CollectionViewSource{Source = "myDataSource"}.View;

然后当您需要更改集合视图源时:

cSource = new CollectionViewSource{Source = "newDataSource"}.View;

然后,如果它是一个数据网格,你会调用:

DG.ItemsSource = cSource;
DG.Items.Refresh();

Datagrid 现在将显示更新的源数据。

于 2019-02-07T20:13:42.983 回答