3

在 MVVM 模式中,是否可以接受甚至可以在后面的视图代码中访问 ViewModel 属性?

我有一个可观察的集合,它填充在 ViewModel 中。我需要在视图中使用它来绑定到带有链表的无尽代码。IE

    private LinkedList<Border> tickerForex = new LinkedList<Border>();

    public ForexBuy()
    {
        InitializeComponent();
        DataContext = new ForexViewModel();
    }

    private void InitializeForexTicker()
    {
        CanvasForexBuyTicker.Children.Clear();
        foreach (var currency in DataContext.Currencies) //Is this possible/allowable???
        {
           AddTickerItem(currency);
        }

        CanvasForexBuyTicker.Dispatcher.BeginInvoke(DispatcherPriority.Background, new DispatcherOperationCallback(delegate
        { var node = tickerForex.First;

            while (node != null)
            {
                if (node.Previous != null)
                {
                    Canvas.SetLeft(node.Value, Canvas.GetLeft(node.Previous.Value) + node.Previous.Value.ActualWidth + gap);
                }
                else
                {
                    Canvas.SetLeft(node.Value, CanvasForexBuyTicker.Width + gap);
                }

                node = node.Next;
            }

            return null;

        }), null);

}

void AddTickerItem(Currency currency)
    {
        Border border = new Border();
        border.Background = new SolidColorBrush(Color.FromArgb(255, 0, 99, 99));

        if (currency.IsUpward == 0)
        {
            border.Background = new SolidColorBrush(Color.FromArgb(255, 255, 153, 0));
        }

        border.BorderThickness = new Thickness(3);
        border.BorderBrush = new SolidColorBrush(Colors.White);
        border.CornerRadius = new CornerRadius(10);
        border.Width = Double.NaN;
        border.Height = 35;

        UIHelper.CanvasAutoSize canvas = new UIHelper.CanvasAutoSize();
        canvas.Background = Brushes.Green;  
        canvas.Tag = currency;
        canvas.Height = Double.NaN;

        TextBlock tb = new TextBlock
        {
            Text = currency.Code + " " + currency.Sell + " ",
            FontSize = 22,
            FontWeight = FontWeights.Bold,
            Foreground = Brushes.Black
        };

        tb.SetValue(Canvas.LeftProperty, 8d);
        tb.SetValue(Canvas.TopProperty, 2d);
        canvas.Children.Add(tb);

        tb.TouchDown += TouchTickerItem;

        border.Child = canvas;

        CanvasForexBuyTicker.Children.Add(border);
        Canvas.SetTop(CanvasForexBuyTicker, 3);
        Canvas.SetLeft(CanvasForexBuyTicker, 0);

        tickerForex.AddLast(border);
    }

对于调度程序是否应该从 ViewModel 触发或是否在后面的视图代码中使用它,我有点迷茫。

4

2 回答 2

9

如果问题只是关于如何从后面的代码访问 ViewModel,您可以简单地将 DataContext 转换为正确的类型:

var viewModel = (MyViewModel)DataContext;

foreach (var currency in viewModel.Currencies)
{
    ...
}

这是否可以接受是一个品味问题。我看不出通过视图的 XAML 中的绑定或一段代码隐藏来访问视图模型有任何根本区别。

于 2012-12-06T23:23:39.427 回答
-2

简短的回答:不。

您不应该将特定于业务或模型的代码放在后面的代码中。只有特定于 VIEW 的代码应该放在后面的代码中。

你为什么要声明一个List<Border>. 对我来说听起来很奇怪。你到底想做什么?

于 2012-12-06T21:56:52.997 回答