【问题标题】:Contentcontrol unable to update when content property changed from call within the loaded usercontrol当内容属性从加载的用户控件中的调用更改时,内容控件无法更新
【发布时间】:2013-03-14 10:28:10
【问题描述】:

我有一个包含单个 ContentControl 的 MainView,当应用程序加载时,ContentControl 会加载一个默认的用户控件。

<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
    }

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

我从控件中发送的命令对 Contentcontrol 有什么保留,使其不想加载其他内容?

【问题讨论】:

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


    【解决方案1】:

    您需要通知 UI 发生了变化。实现 INotifyPropertyChanged 并将其添加到 ActiveControl 分配中:

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

    Here is the documentation

    编辑#1

    我认为您应该使用用户控件中的按钮来绑定到主窗口中的命令。这比尝试将主窗口视图模型传递给用户控件要好,后者会创建依赖关系并违反 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>
    

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

    希望对你有帮助

    【讨论】:

    • 嗨,感谢您的回复,我实际上实现了一个 ModelViewBase,它是 INotifyProperty,所​​以我的“ActiveControl”看起来像这样:public object ActiveControl { get { return activeControl; } set { ActiveControl = value; RaisePropertyChanged("ActiveControl "); } }我是否需要手动更新 GUI来自 ViewModel 还是足够了?
    • 我想我需要查看更多代码,活动控件属性是如何定义的?你能展示你的主视图数据上下文是如何定义的吗?
    • 嗨,J King,我为你编译了一个小例子,你可以看看我是怎么做的:link
    • 太棒了,看看我的编辑,它有一个使用来自 usercontrol 的 ICommand 的按钮
    • 你是我的英雄,非常感谢!现在,当我在 TabControl-Tab 中托管一个内容控件并想从内部添加一个选项卡时,我只需要弄清楚如何做同样的事情(找到窗口),但我猜它的想法相同(但现在祖先是 TabControl而不是 Window,所以我需要上一层)。
    猜你喜欢
    • 2019-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-11
    • 1970-01-01
    • 2019-10-13
    • 1970-01-01
    • 2015-03-08
    相关资源
    最近更新 更多