我使用WPF和Caliburn Micro框架。 该程序以GameViewModel.cs启动,它正确地与GameView.xaml同步。
从GameViewModel.cs我创建了四个new PlayerViewModel()
,它与PlayerView.xaml正确同步。在PlayerView.xaml中我有几个绑定,一切都正确绑定,没有问题,正如我所希望的那样更新..
但是在“输出”窗口中,我收到了各种错误,即PlayerView的Bindings无法绑定到GameViewModel.cs。
现在,很棒的是程序按预期工作,但所有这些错误让我担心会检查我做错了什么。请帮帮我,这里发生了什么?
(我的猜测是它的Caliburn相关,它试图将x:Name
绑定到GameViewModel中的某些东西,因为它是启动项目。如果我碰巧在标记,如何更改它以正确绑定?)
错误如下:
System.Windows.Data Error: 40 : BindingExpression path error: 'TransformScaleX' property not found on 'object' ''GameViewModel' (HashCode=24649639)'. BindingExpression:Path=TransformScaleX; DataItem='GameViewModel' (HashCode=24649639); target element is 'TextBlock' (Name='ScaleX'); target property is 'Text' (type 'String')
System.Windows.Data Error: 40 : BindingExpression path error: 'TransformScaleY' property not found on 'object' ''GameViewModel' (HashCode=24649639)'. BindingExpression:Path=TransformScaleY; DataItem='GameViewModel' (HashCode=24649639); target element is 'TextBlock' (Name='ScaleY'); target property is 'Text' (type 'String')
列表继续有点,同样的错误也适用于其他属性。 代码如下,我裁掉了(貌似?)无关的位:
//This works fine
public class GameViewModel : PropertyChangedBase
{
private Game _model;
public GameViewModel() { _model = new Game(this); }
private PlayerViewModel _player1 = new PlayerViewModel("player1");
public PlayerViewModel Player1 { get { return _player1; } set { _player1 = value; NotifyOfPropertyChange("Player1"); } }
}
//This works fine too.
<UserControl>
<Grid Width="1280" Height="720" Background="Cyan">
<local:PlayerView cal:View.Model="{Binding Player1}" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="10,220,0,0"/>
</Grid>
</UserControl>
//Works fine
public class PlayerViewModel : PropertyChangedBase
{
private Player _model;
public PlayerViewModel(string name)
{
Username = name;
_model = new Player(this);
}
//NotifyOfPropertyChange is handled properly elsewhere
public string TransformScaleX { get; set; }
public string TransformScaleY { get; set; }
}
//All binds with no issues.
<UserControl>
<Grid Width="288" Height="55">
<TextBlock x:Name="ScaleX" Visibility="Hidden" Text="{Binding TransformScaleX}"/>
<TextBlock x:Name="ScaleY" Visibility="Hidden" Text="{Binding TransformScaleY}"/>
</Grid>
</UserControl>
答案 0 :(得分:0)
第一条错误消息表明,当DataContext是GameViewModel而不是PlayerViewModel时,您正在尝试绑定到TransformScaleX
属性。属性TransformScaleX
的第二条错误消息表示类似的事情。
尝试检查此问题中发布的第二个UserControl
。当您预期它是DataContext
时,GameViewModel
似乎是PlayerViewModel
对象。
答案 1 :(得分:0)
<UserControl>
<Grid Width="1280" Height="720" Background="Cyan">
<ContentControl cal:View.Model="{Binding Player1}" cal:View.Content="PlayerView" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="10,220,0,0"/>
</Grid>
</UserControl>
这应该有效。基本上你得到错误,因为它无法找到属性TransformScaleY / TransformScaleX的路径。由于viewmodel正在寻找要绑定到当前视图的属性。这也与首先混合mvvm paradigms viewmodel / view有关。只需知道你希望它如何与其他一切一起玩。