2009-12-11 79 views
0

我有以下測試用例xaml。我可以在沒有警告的情況下重新掛接或暫停BindingExpression嗎?

<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,但即使這引發了這個警告。我應該忍受這個警告嗎?

+0

您是否嘗試過? – 2009-12-11 00:57:30

+0

我想我不能。綁定源不是DependencyProperty。當我這樣做時,我會得到這個例外。 無法在'Binding'類型的'Source'屬性上設置'DynamicResourceExtension'。 'DynamicResourceExtension'只能在DependencyObject的DependencyProperty上設置。 – 2009-12-11 01:01:57

回答

1

最後,發現使用DynamicResource而不是靜態資源答案

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); 
    } 
} 
相關問題