当内容属性从已加载的usercontrol中的调用更改时,Contentcontrol无法更新

时间:2013-03-25 01:37:21

标签: wpf mvvm user-controls mvvm-light contentcontrol

我有一个包含单个ContentControl的MainView,ContentControl会在应用程序加载时加载默认的usercontrol。

<ContentControl x:Name="MainContentArea" Content="{Binding ActiveControl}"/>

加载的用户控件,加载一些插件(不相关),在从组合框中选择项目时,它会使用MVVM Light的ViewModelLocator概念触发Parent(MainViewModel)中存在的ICommand。

private void CreateSelectedPlugin(IExtendedUIViewFactory plugin)
    {
        var pluginStartControl = plugin.Create();
        _locator.Main.DefaultCommand.Execute(pluginStartControl);
    }

问题是ContentControl没有更新,我可以设置断点并看到命令在MainViewModel中执行,并且我发送的变量是有效的。

public ICommand DefaultCommand { get; set; }
    public MainWindowViewModel()
    {
        DefaultCommand = new RelayCommand<object>(LoadSection, o => true);
    }

    private void LoadSection(object plugin)
    {
        ActiveControl = plugin;
        //does not matter if i set it to null here
    }

调用刚刚将ContentControl设置为null的LoadSection或testfunction,从MainView / MainViewModel,它按预期工作。

我在控件中发送的命令对Contentcontrol有什么作用,使得它不想加载其他内容?

1 个答案:

答案 0 :(得分:0)

您需要通知UI已发生更改。实现INotifyPropertyChanged并将其添加到ActiveControl赋值:

private void LoadSection(object plugin)
{
    ActiveControl = plugin;
    NotifyPropertyChanged();
}

Here is the documentation

修改#1

我认为您应该使用用户控件中的按钮绑定到主窗口中的命令。这比尝试将mainwindow viewmodel传递给usercontrol要好,后者会创建依赖项并违反MVVM模式。将此按钮添加到您给我的样本中的usercontrol1

        <Button Content="Set MyContent to null using binding to main window command" Height="40" Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}},Path=DataContext.PublicCommand}"></Button>

它使用主窗口中命令的相对绑定,在我的应用程序中,我使用一个主窗口来保存所有用户控件/视图。这样我就可以控制显示的内容并仅在一个我知道永远可用的地方使用命令定义。

希望这会有所帮助