我有一個具有高度100的Canvas
和寬度1920WPF ActualWidth的是零
在控制的負荷,我去到外部源的用戶控件,下載一個文本文件,並添加TextBlock
s到帆布。然後我想創建一個字幕滾動效果,這應該工作得很好,除了我將TextBlock
s添加到Canvas
之後,我需要獲取它們的寬度以用於計算目的,但ActualWidth
屬性始終爲零。
下面是一些代碼:
private readonly LinkedList<TextBlock> textBlocks = new LinkedList<TextBlock>();
public LocalNewsControl()
{
Loaded += LocalNewsControlLoaded;
}
private void LocalNewsControlLoaded(object sender, RoutedEventArgs e)
{
LoadDataContext();
}
private void LoadDataContext()
{
DataContext = new NewsItemsViewModel((exception) => LoadNewsItems());
}
private void LoadNewsItems()
{
var viewModel = (NewsItemsViewModel)DataContext;
NewsCanvas.Children.Clear();
textBlocks.Clear();
foreach (var newsViewModel in viewModel.NewsItems)
{
var tb = new TextBlock
{
Text = newsViewModel.Headline,
FontSize = 28,
FontWeight = FontWeights.Normal,
Foreground = Brushes.Black
};
NewsCanvas.Children.Add(tb);
Canvas.SetTop(tb, 20);
Canvas.SetLeft(tb, -999);
textBlocks.AddLast(tb);
}
Dispatcher.BeginInvoke(new Action(() =>
{
var node = textBlocks.First;
while (node != null)
{
if (node.Previous != null)
{
//THIS IS WHERE ActualWidth is always ZERO
var left = Canvas.GetLeft(node.Previous.Value) + node.Previous.Value.ActualWidth + Gap;
Canvas.SetLeft(node.Value, left);
}
else
Canvas.SetLeft(node.Value, NewsCanvas.Width + Gap);
node = node.Next;
}
}));
}
TextBlock中是不可見的,未加載,因此它沒有屬性ActualWidth。我已經解決了與ItemsControl類似的問題,但我不確定Canvas。嘗試像LayoutUpdated,SizeChanged等事件。 – vorrtex 2010-12-21 11:09:07