[英]In MVVM is it acceptable to access the ViewModel in the view's code behind?
在 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 觸發或者是否在后面的視圖代碼中使用它,我有點迷茫。
如果問題只是關於如何從后面的代碼訪問 ViewModel,您可以簡單地將 DataContext 轉換為正確的類型:
var viewModel = (MyViewModel)DataContext;
foreach (var currency in viewModel.Currencies)
{
...
}
這是否可以接受是一個品味問題。 在通過視圖的 XAML 中的綁定或通過一段代碼隱藏訪問視圖模型方面,我沒有看到任何根本區別。
簡短的回答:不。
您不應該將特定於業務或模型的代碼放在后面的代碼中。 只有特定於 VIEW 的代碼才應該放在代碼后面。
你為什么要聲明一個List<Border>
。 我聽起來很奇怪。 你到底想做什么?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.