6

我有一个用户控件,其Canvas高度为 100,宽度为 1920。

在加载控件时,我转到外部源,下载一个文本文件并将TextBlocks 添加到 Canvas。然后我想创建一个应该可以正常工作的选框滚动效果,除了将TextBlocks 添加到之后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;
        }
    }));
}
4

4 回答 4

5

You could always attach a delgate to the PropertyMetatdata/OnValueChanged and when ActualHeight/ActualWidth changes from 0 to something, adjust your scrolling, ActualWidth/ActualHeight will have a value once its rendered at least once:

LocalNewsControl()
{
    var descriptor = DependencyPropertyDescriptor.FromProperty(ActualWidthProperty, typeof(TextBlock));
    if (descriptor != null)
        descriptor.AddValueChanged(myTextBlock, ActualWidth_ValueChanged);
}

private void ActualWidth_ValueChanged(object a_sender, EventArgs a_e)
{
   //Modify you scroll things here
   ...
}
于 2010-12-21T12:04:45.727 回答
3

If you want to stick with your dispatcher call - set the priority to loaded then it will be called same time as the loaded event and you should have a value. There is an overload on BeginInvoke that takes a priority also.

于 2010-12-21T11:44:55.277 回答
2

任何ControlActualHeightor在它们是> > >ActualWidth之前总是为零。LoadedMeasuredArrangedRendered

在您的情况下,我建议您使用Loaded或使用SizeChanged它对TextBlock您有利。

于 2010-12-21T10:52:33.893 回答
0

Is there any particular reason for using Canvas for the layout of the TextBlocks? If not, you'd better use a StackPanel with Horizontal orientation, it will handle the layout math for you.

于 2010-12-21T11:07:32.363 回答