简体   繁体   English

MVVM和更新属性

[英]MVVM and updating properties

I'm still trying to get my head around MVVM so apologies if this question is basic. 我仍在努力了解MVVM,因此很抱歉如果这个问题很简单。

My program displays some text on screen, but depending on the status of another property will depend on the color of the text. 我的程序在屏幕上显示了一些文本,但是取决于另一个属性的状态将取决于文本的颜色。

In my mind, I could do this in 2 ways. 在我看来,我可以通过两种方式做到这一点。

  1. When the Status property is changed, the color is changed from within the setter. 更改状态属性后,颜色将从设置器中更改。 EG (Pseudo code) EG(伪代码)

     private LogDetails.LogStatus? logStatus; public LogDetails.LogStatus? LogStatus { get { return logStatus; } set { Color color = //logic to work out the color Color = color; } } 
  2. I think this can be done via the OnPropertyChanged (which I can research myself). 我认为可以通过OnPropertyChanged(我可以自己研究)完成此操作。

My question is, since I am given 2 options to complete my simple task, is one better than the other in certain situations, is one more depreciated/old or am I forced to use option 2 just to appease the MVVM pattern? 我的问题是,由于给了我2个选项来完成我的简单任务,在某些情况下,一个选项比另一个选项好吗?是另一个折旧/旧了吗?还是我被迫仅使用选项2来安抚MVVM模式?

I would assume that if I eventually require 2 way binding (so I can update the status from a GUI for example) then the MVVM is better, but as it stands today, does any one have any thoughts? 我假设如果我最终需要2种方式的绑定(例如,我可以从GUI更新状态),那么MVVM会更好,但是就目前而言,任何人有什么想法吗?

You should simply write a custom IValueConverter that takes the LogStatus and translates it to a color. 您应该简单地编写一个自定义IValueConverter ,它接受LogStatus并将其转换为颜色。 Bind the Text directly to LogStatus and bind the Color of the control to the LogStatus using the converter. Text直接绑定到LogStatusLogStatus使用转换器将控件的Color绑定到LogStatus

The code is really simple (just implement one method, add the converter as a XAML resource and reference it in your binding), but you can see a similar example here . 代码真的很简单(只需实现一种方法,将转换器添加为XAML资源并在绑定中引用它即可),但是您可以在此处看到类似的示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM