【问题标题】:Activation/deactivation of toolbar buttons using Prism使用 Prism 激活/停用工具栏按钮
【发布时间】:2011-03-28 16:04:40
【问题描述】:

我正在学习 Prism 框架,并且已经取得了进展。但我想知道如何创建工具栏(和上下文菜单),每个模块可以在其中注册自己的按钮。

对于这个例子,我希望所有按钮都驻留在位于我的 Shell 中的同一个 ToolBar 控件中。工具栏ItemsSource 绑定到视图模型中ObservableCollection<FrameworkElement> 类型的ToolBarItems 属性。可以使用ToolBarRegistry 服务将元素添加到此集合中。这是 ViewModel:

public class ShellViewModel
{
    private IToolBarRegistry _toolBarRegistry;
    private ObservableCollection<FrameworkElement> _toolBarItems;

    public ShellViewModel()
    {
        _toolBarItems = new ObservableCollection<FrameworkElement>();
        _toolBarRegistry = new ToolBarRegistry(this);
    }

    public ObservableCollection<FrameworkElement> ToolBarItems
    {
        get { return _toolBarItems; }
    }
}

请注意,如果结果证明是正确的解决方案,FrameworkElement 类型的集合将被重构为更具体的类型。

我的ToolBarRegistry有注册图片按钮的方法:

public void RegisterImageButton(string imageSource, ICommand command)
{
    var icon = new BitmapImage(new Uri(imageSource));

    var img = new Image();
    img.Source = icon;
    img.Width = 16;

    var btn = new Button();
    btn.Content = img;
    btn.Command = command;

    _shellViewModel.ToolBarItems.Add(btn);
}

我从OrderModule 调用此方法,按钮正确显示。到目前为止一切顺利。

问题是我如何控制何时应该再次删除这些按钮。如果我导航到另一个模块中的视图(有时是同一模块中的另一个视图),我希望这些特定于模块的按钮再次隐藏。

您对如何执行此操作有任何建议吗?我是以错误的方式解决这个问题,还是我可以修改我已经拥有的?你是怎么解决这个问题的?

【问题讨论】:

    标签: wpf mvvm prism toolbar


    【解决方案1】:

    我不会在ObservableCollection 中插入Button 实例。请考虑这种方法:

    为工具栏按钮创建 ViewModel

    class ToolBarButtonViewModel : INotifyPropertyChanged
    {
        // INotifyPropertyChanged implementation to be provided by you
    
        public string ImageSource { get; set; }
        public ICommand Command { get; set; }
        public bool IsVisible { get; set; }
    }
    

    那么当然要把ToolBarItems的类型改成这些的集合。

    在您的ShellView 中,为ToolBarButtonViewModel 添加DataTemplate,并将您的工具栏控件的ItemsSource 绑定到 ViewModel 集合,例如:

    <DataTemplate>
        <Button Command="{Binding Command}">
            <Button.Content>
                <Image Source="{Binding ImageSource}" />
            </Button.Content>
        </Button>
    </DataTemplate>
    

    您现在可以使用BooleanToVisibilityConverterButton.Visibility 绑定到IsVisible 来解决您眼前的问题。

    作为额外奖励,您还可以:

    • 完全从 XAML 更改工具栏按钮的视觉外观
    • 将工具栏按钮的可视树的任何属性绑定到ToolBarButtonViewModel 上的相应属性

    更新

    启用/禁用按钮的机制取决于您的应用程序的具体情况。有很多选择——这里有一些(阅读时请记住this chart):

    • 在您的视图或视图模型中实现INavigationAware,并根据需要启用/禁用按钮
    • 将处理程序附加到感兴趣区域的events of IRegionNavigationService,并让处理程序启用或禁用按钮
    • 通过您自己的代码 (CustomNavigationService) 路由所有导航并决定在其中做什么

    【讨论】:

    • 你说得对,这实际上是我在写下我将重构 FrameworkElement 类型时的想法,如果这被证明是正确的解决方案。但是,我仍然看不到如何管理 IsVisible 属性。如果用户离开视图/模块,然后将所有按钮的可见性设置为隐藏,我可以在哪里注册?
    猜你喜欢
    • 1970-01-01
    • 2020-09-10
    • 2021-05-31
    • 1970-01-01
    • 2011-05-01
    • 2013-03-05
    • 2019-05-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多