gpt4 book ai didi

c# - 在 MVVM 中,在 View 的代码后面访问 ViewModel 是否可以接受?

转载 作者:行者123 更新时间:2023-11-30 19:43:52 25 4
gpt4 key购买 nike

在 MVVM 模式中,是否可以接受甚至可以访问隐藏在 View 代码中的 ViewModel 属性?

我有一个填充在 ViewModel 中的可观察集合。我需要在 View 中使用它来绑定(bind)到带有链表的无尽自动收报机。即

    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 触发还是在后面的 View 代码中使用它,我有点迷茫。

最佳答案

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

var viewModel = (MyViewModel)DataContext;

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

这是否可以接受是个人喜好问题。在通过 View 的 XAML 中的绑定(bind)或通过一段代码隐藏访问 View 模型方面,我没有看到任何根本区别。

关于c# - 在 MVVM 中,在 View 的代码后面访问 ViewModel 是否可以接受?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13753228/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com