从已知视图访问属性他的viewmodel

时间:2013-09-03 14:47:16

标签: c# wpf mvvm parameters

我有一个包含用户控件的视图,其中包含自己的视图&视图模型。

用户控制它的视图如下所示:

<UserControl.DataContext>
    <viewmodel:TimePickerViewModel x:Name="timePickerViewModel"/>
</UserControl.DataContext>

在usercontrol的viewmodel中,我有一个属性ValidTime:

public DateTime? ValidTime
{
    get { return validTime; }
    set
    {
        validTime = value;
        OnPropertyChanged("ValidTime");
    }
}

在包含usercontrol的视图中,我需要访问属性ValidTime:

<timepicker:TimePickerView Grid.Row="0" x:Name="timePicker"/>
<Button Grid.Row="1" Content="Plan" Command="{Binding PlanCommand}" CommandParameter="    {Binding ElementName=timePicker, Path=ValidTime}"/>

在上一个视图的viewmodel中,我有这个:

public ICommand PlanCommand
{
    get { return planCommand ?? new RelayCommand<DateTime?>(Plan); }
}

void Plan(DateTime? date)
{
    if(pickedMagnet != null)
            pickedMagnet.StartDatePlanned = date;
}

但是DateTime?我在Plan方法中收到的参数始终为null。但是在调试模式下,我看到属性ValidTime被赋值。我也试过这个:

<Button Grid.Row="1" Content="Plan" Command="{Binding PlanCommand}" CommandParameter="{Binding ElementName=timePicker.timePickerViewModel, Path=ValidTime}"/>

<Button Grid.Row="1" Content="Plan" Command="{Binding PlanCommand}" CommandParameter="{Binding ElementName=timePicker, Path=timePickerViewModel.ValidTime}"/>

但这些都不起作用。

任何人都知道我的情况的解决方案或最佳做法?

1 个答案:

答案 0 :(得分:0)

经过一番尝试,我就这样修好了。

CommandParameter="{Binding ElementName=timePicker, Path=DataContext.ValidTime}"
相关问题