我是WPF的新手,试图尽可能地坚持MVVM模式。到目前为止一直很好,除了我遇到了从我的模型中绑定某些属性的问题。
所以我有我在模型中公开的非静态属性,但它们只能在模型中更改。我运行了一些功能,它可以完成大量工作,并通过一系列我公开过来查看的参数来跟踪它正在做什么。
当我在ViewModel中有属性时,我很好 - 我可以更新这些,因为我已经实现了INotifyPropertyChanged。我已经看到有时人们已经在他们的模型中实现了这个,所以我尝试了但不知道INotifyPropertyChanged如何真正起作用我不知道是否还需要做任何事情才能让它在模型中运行正常。< / p>
我试图在我的ViewModel中创建一个从Model读取的属性,我将xaml绑定到此但是因为我无法从ViewModel改变它,我遇到了告诉UI它已被更改的相同问题。目前我有绑定直接,而我试图想出来但我的目标是能够绑定到ViewModel中的一个属性,它只是从模型中获取值。
任何人都可以给我一个简单的单向绑定到标签/文本块等基本控件的简单示例,当它从模型中发生变化时会自动更新吗?
为了完整性,这里是我所拥有的简化版本,包括示例xaml(显示绑定到Model属性以及绑定到ViewModel中的属性)。绑定有效,因为如果我在模型中进行更改,它们就会出现在设计器和初始构建中。
模型是我自己的代码,我可以添加/删除任何东西以使其正常工作。也许这是相当直截了当的,但我现在还没有看到解决方案,也没有在论坛上看到任何对我有意义的事情。
谢谢!
模型中的public enum TempValues { zero, pos10, pos50, pos100 }
namespace AutoCalModel
{
public class AutoCalibration : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = this.PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
private TempValues _TempRelayValue = TempValues.zero;
public TempValues TempRelayValue
{
get { return _TempRelayValue; }
set
{
if (!value.Equals( _TempRelayValue))
{
_TempRelayValue = value;
NotifyPropertyChanged("TempRelayValue");
}
}
}
// rest of class including code that changes the above TempRelayValue
// accessed through the public property only
}
}
xaml <StackPanel Orientation="Horizontal" VerticalAlignment="Center">
<TextBlock Name="labelPrsTitle" Text="Prs:" Margin="2,0,2,0"/>
<TextBlock Name="labelPrsValue" Text="{Binding Path=currentPrsValueString, Mode=OneWay}" Margin="2,0,5,0"/>
<Separator Margin="5,0,5,0"/>
<TextBlock Text="Temp Relay:" Margin="5,0,2,0"/>
<TextBlock Text="{Binding Path=TempRelayValue, Converter={StaticResource tempValuesConverter}, Mode=OneWay}" Margin="2,0,5,0">
<TextBlock.DataContext><Model:AutoCalibration/></TextBlock.DataContext>
</TextBlock>
</StackPanel>
答案 0 :(得分:3)
我的一位朋友也犯了同样的错误。
// rest of class including code that changes the above **_TempRelayValue**
在这里,您已经定居,您将更改 _tempRelayVAlue 变量。变量没有与之关联的任何通知。所以你需要做的是通过下面的proerty设置值,这应该通知UI模型或VM值已经被打开。因为你已经将通知实现到不在变量中的属性中。
TempRelayValue = yourvalues;