从DataTemplate绑定ContentControl仅在构造函数中工作?

时间:2012-03-11 23:08:15

标签: c# wpf

我正在尝试使用ICommands切换内容控件的内容。现在设置此属性在构造函数中有效,但在任何命令中都不起作用。

我的app.xaml

中有这个
<Application.Resources>
    <vm:ViewModelLocator x:Key="Locator"
                         d:IsDataSource="True" />
    <DataTemplate DataType="{x:Type vm:HomeViewModel}">
        <views:HomeView />
    </DataTemplate>
    <DataTemplate DataType="{x:Type vm:DeviceViewModel}">
        <views:DeviceView />
    </DataTemplate>
</Application.Resources>

这是ShellView.xaml的一个片段(这是包含我想要更改的内容控件的视图):

<ContentControl Content="{Binding Path=CurrentViewModel}" />

此处显示按钮绑定的另一个片段:

<Button Content="Button"
                Height="23"
                Name="button2"
                Width="75"
                Command="{Binding Path=DeviceViewCommand}" />

这是ShellViewModel的构造函数。正如我所说设置CurrentViewModel在这里工作。 (你会注意到我设置了设备,然后回家作为测试。)

    public ShellViewModel()
    {
        CurrentViewModel = ShellViewModel._deviceViewModel;
        CurrentViewModel = ShellViewModel._homeViewModel;
        HomeViewCommand = new RelayCommand(() => ExecuteHomeViewCommand());
        DeviceViewCommand = new RelayCommand(() => ExecuteDeviceViewCommand());
        LogOut = new RelayCommand(() => LogOutExecute(), () => true);

    }

    private void ExecuteDeviceViewCommand()
    {
        CurrentViewModel = ShellViewModel._deviceViewModel;

    }

我在这里做错了吗?

这也是当前视图模型更改的属性。应该早点补充一下。

public ViewModelBase CurrentViewModel
    {
        get
        {
            return _currentViewModel;
        }
        set
        {
            if (_currentViewModel == value)
                return;
            _currentViewModel = value;
            RaisePropertyChanged("CurrentViewModel");
        }
    }

3 个答案:

答案 0 :(得分:1)

如果我正确理解了您的问题,您可以为CurrentViewModel创建VM类,从INotifyPropertyChanged继承它并修改它的属性。 Bindng应该是单向的。

答案 1 :(得分:1)

我会退后一步,给ContentControl一个名称,并尝试直接设置内容属性以查看是否有其他错误。此外,如何为ContentControl设置DataContext?尝试在setter上设置断点。您还可以在输出窗口中检查Bindings上的错误。

答案 2 :(得分:0)

所以我必须通过打破MVVM模式来解决这个问题。我在shell视图模型的代码中使用了MVVM light messenger类,只需将内容控件设置为新视图,然后将其数据上下文设置为ShellViewModel的当前视图模型。

我对此解决方案并不完全满意,但它确实可以正常运行。