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

时间:2009-12-11 00:50:02

标签: wpf data-binding c#-3.0

我有以下测试用例xaml。

<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 个答案:

答案 0 :(得分:1)

最后,找到答案

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