代码之家  ›  专栏  ›  技术社区  ›  Andrew Keith

我可以在没有警告的情况下重新附加或挂起BindingExpression吗?

  •  0
  • Andrew Keith  · 技术社区  · 15 年前

    <Window.Resources>
        <XmlDataProvider x:Key="testDS1">
            <x:XData>
                <root xmlns="">
                    <item>1</item>
                    <item>1</item>
                </root>
            </x:XData>
        </XmlDataProvider>
    </Window.Resources>
    <StackPanel>
        <ListBox ItemsSource="{Binding Source={StaticResource testDS1},XPath=/root/item}"/>
        <Button Content="Change" Click="OnChangeClicked"/>
    </StackPanel>
    

    这将显示一个数字列表框。然后我执行这个代码。

        public void OnChangeClicked(object sender, RoutedEventArgs e)
        {
            XmlDataProvider ds = Resources["testDS1"] as XmlDataProvider;
            string xml = "<root><item>1</item></root>";
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xml);
            ds.Document = doc;
        }
    

    System.Windows.Data Error: 43 : BindingExpression with XPath cannot bind to non-XML object.; XPath='/root/item' BindingExpression:Path=; DataItem='XmlDataCollection' (HashCode=40644060); target element is 'ListBox' (Name=''); target property is 'ItemsSource' (type 'IEnumerable') XmlDataCollection:'MS.Internal.Data.XmlDataCollection'
    

    但是,ListBox绑定正确并且具有正确的值。从读到这里 thread ,它提到这种行为是正常的,绑定表达式已重新连接。如何消除此警告?我尝试过BindingOperations.ClearBinding,但即使这样也触发了此警告。我应该接受这个警告吗?

    1 回复  |  直到 15 年前
        1
  •  1
  •   Andrew Keith    15 年前

    最后,我找到了答案

    public void OnChangeClicked(object sender, RoutedEventArgs e)
    {
        XmlDataProvider ds = Resources["testDS1"] as XmlDataProvider;
        string xml = "<root><item>1</item></root>";
        XmlDocument doc = new XmlDocument();
        doc.LoadXml(xml);
        using(ds.DeferRefresh())
        {
           ds.Document = doc;
           ds.XmlNamespaceManager = new XmlNamespaceManager(doc.NameTable);
        }
    }