我正在加載一些我創建的XAML頁面,它們中有一些數據綁定。但是,當我在運行時加載這些XAML文件時,它們的數據綁定不再起作用。我想知道這是否是某種範圍或路徑問題,或者您是否無法做到。當您的XAML在運行時加載時,您可以綁定數據嗎?
這裏是我正在加載XAML
using (XmlReader rdr = XmlReader.Create(@".\TwitterModule\TwitterModule.xaml"))
{
Canvas twitter = XamlReader.Load(rdr) as Canvas;
contentRoot.Children.Add(twitter);
}
這裏是我最後的XAML
<!--XAML -->
<Canvas xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:LocalTrendsDS="clr-namespace:LocalTrendsDS;assembly=LocalTrendsDS" />
<Canvas.Resources>
<XmlDataProvider x:Key="TweetCounter" Source="..\temp\TweetCounter.xml" />
<LocalTrendsDS:LocalTrends x:Key="LocalTrendsDataSource" />
</Canvas.Resources>
<Canvas x:Name="root" Height="479" Width="877"
DataContext="{Binding Source={StaticResource TweetCounter}}">
<TextBlock x:Name="Number"
Canvas.Left="86.744" LineHeight="122.919" TextAlignment="Right" TextWrapping="Wrap" Width="425.372"
Text="{Binding Mode=OneWay, XPath=/Count}" />
</Canvas>
<Canvas x:Name="_3a" Height="383" Canvas.Left="1971" Canvas.Top="107" Width="362"
DataContext="{Binding Source={StaticResource LocalTrendsDataSource}}">
<TextBlock x:Name="TrendList" FontSize="16.449" Canvas.Left="-0.806" LineHeight="16.449" TextAlignment="Left" TextWrapping="Wrap" Canvas.Top="112.155" Height="127.829"><TextBlock.RenderTransform>
<MatrixTransform Matrix="2.334,0,0,2.334,0,0"/>
</TextBlock.RenderTransform>
<Run Foreground="#FF9900EB" FontFamily="Hiruko Alternate" Text="1. "/>
<TextBlock Foreground="#FFFFFFFF" FontFamily="Segoe Semibold" Text="{Binding CurrentLocalTrends[0].Value, Mode=Default}"/><LineBreak/>
<Run Foreground="#FFDB0072" FontFamily="Hiruko Alternate" Text="2. "/>
<TextBlock Foreground="#FFFFFFFF" FontFamily="Segoe Semibold" Text="{Binding CurrentLocalTrends[1].Value, Mode=Default}"/><LineBreak/>
<Run Foreground="#FFFF0F1B" FontFamily="Hiruko Alternate" Text="3. "/>
<TextBlock Foreground="#FFFFFFFF" FontFamily="Segoe Semibold" Text="{Binding CurrentLocalTrends[2].Value, Mode=Default}"/><LineBreak/>
<Run Foreground="#FFFF6E05" FontFamily="Hiruko Alternate" Text="4. "/>
<TextBlock Foreground="#FFFFFFFF" FontFamily="Segoe Semibold" Text="{Binding CurrentLocalTrends[3].Value, Mode=Default}"/><LineBreak/>
<Run Foreground="#FFFF9F01" FontFamily="Hiruko Alternate" Text="5. "/>
<TextBlock Foreground="#FFFFFFFF" FontFamily="Segoe Semibold" Text="{Binding CurrentLocalTrends[4].Value, Mode=Default}"/><LineBreak/>
</TextBlock>
</Canvas>
</Canvas>
答:這是一個路徑問題的,感謝您的幫助。我能夠在運行時加載的XAML中綁定XmlDataProvider和其他對象數據源。巨大的時間節省。在Blend中構建UI並在黑暗中綁定它們。
輸出窗口中是否有任何錯誤消息? Canvas是否設置了DataContext? – JustABill 2010-06-03 23:41:29
請不要在標題中重複標籤(「C#WPF」) – 2010-06-04 01:10:23
沒有錯誤信息,只是在TextBlock中沒有任何顯示。我會給出這兩個建議,今天試一下,如果他們幫我找到問題,請轉發。 – discorax 2010-06-04 16:53:28