DataContext无法使用MVVM

时间:2014-11-13 13:09:40

标签: c# wpf xaml mvvm

我有一个带有以下标签的AccView.xaml UserControl:

<UserControl.DataContext>
    <vm:SetGetAccValues />
</UserControl.DataContext>

<Label x:Name="labelValX" Content="{Binding SensorAcc.X}" HorizontalAlignment="Left" Margin="282,51,0,0" VerticalAlignment="Top" FontSize="30" RenderTransformOrigin="0.519,0.24" Width="88" Height="44"/>        
<Label x:Name="labelValY" Content="{Binding SensorAcc.Y}" Content="{Binding SensorAcc.Y}" HorizontalAlignment="Left" Margin="282,95,0,0" VerticalAlignment="Top" FontSize="30" RenderTransformOrigin="0.519,0.24" Width="88" Height="44"/>       
<Label x:Name="labelValZ" Content="{Binding SensorAcc.Z}" HorizontalAlignment="Left" Margin="282,139,0,0"  VerticalAlignment="Top" Height="48" Width="88" FontSize="30" RenderTransformOrigin="0.759,0.459"/> 

如我的xaml所示,我已将DataContext声明为SetGetAccValues类:

public GetAccNotifications.Accelerometer SensorAcc { get; set; }    
public bool SensorInitialiseringOK { get; set; }    
public bool SensorOK { get { var Retval = SensorAcc != null && SensorInitialiseringOK == true; return Retval; } }    
public int SensorIndex { get; set; }

public async Task InitializeAsync(GetAccNotifications.Readings readings, int serviceNumb)
{
    if (!SensorOK)
    {
        var tagsAcc = await GetAccNotifications.Accelerometer.CreateAllAsync(GetAccNotifications.Readings.None, this);
        if (tagsAcc.Count <= SensorIndex) return;
        SensorAcc = tagsAcc[SensorIndex].Sensor as GetAccNotifications.Accelerometer;
        SensorInitialiseringOK = SensorAcc != null && tagsAcc[SensorIndex].NError == 0;
    }
    this.DataContext = this;
    if (SensorOK)
    {
        await SensorAcc.InitializeAsync(null, readings, this); 
    }
} 

我实际上是从GetAccNotificaions.Accelerometer子类(INotifyPropertyChanged)中获取X,Y和Z值,我已将其声明为“SensorAcc”。

在这种情况下,以下可能存在DataContext问题:

this.DataContext = this; 

因为视图中的值不会更新。我也尝试在AccView(AccView.xaml.cs)的后台类中实现完全相同,而不是为这个SetGetAccValues类定义DataContext,在这种情况下,它没有任何问题。调试时我拍了一些截图:

AccView.xaml.cs案例:

enter image description here

并且在SetGetAccValues.cs的情况下,三个标签不包含在“this.DataContext”中。这是问题的原因吗?如果是,我该如何处理?,我是否必须在此SetGetAccValues类中包含InitializeComponent()方法?

1 个答案:

答案 0 :(得分:0)

我给了你一个通用答案:

在一个usercontrol中你只绑定到你自己的DependencyProperties,你用ElementName或RelativeSource绑定做到这一点,你永远不应该在UserControl中设置DataContext。

 <UserControl x:Name="myRealUC" x:class="MyUserControl">
   <TextBox Text="{Binding ElementName=myRealUC, Path=MyOwnDPIDeclaredInMyUc, Path=TwoWay}"/>
 <UserControl>

如果您这样做,您可以在任何视图中轻松使用此Usercontrol,如:

<myControls:MyUserControl MyOwnDPIDeclaredInMyUc="{Binding MyPropertyInMyViewmodel}"/>