【问题标题】:How do I have the Click event of a button manipulate another control in MVVM如何让按钮的 Click 事件操纵 MVVM 中的另一个控件
【发布时间】:2013-05-26 10:55:43
【问题描述】:

我正在使用 WPF(4.5) 和 Caliburn.Micro。我试图了解如何让我的视图中的“事件”操纵我的视图中的其他控件。

例如:

我的视图有一个扩展控件、一个按钮和一个 GridView。 GridView 在 Expander 内。当用户单击按钮时,它会调用 VM 中的方法,该方法使用 BindableCollection 填充 gridview。我想要发生的是当该集合有超过 1 个我想自动展开扩展器控件的项目时。

想法?

【问题讨论】:

    标签: c# .net wpf mvvm caliburn.micro


    【解决方案1】:

    您可以绑定到集合中的项目数:

    <Expander IsExpanded="{Binding Path=YourCollection.Length, Converter={StaticResource ResourceName=MyConverter}" />
    

    然后在窗口或用户控件中:

    <UserControl... xmlns:converters="clr-namespace:My.Namespace.With.Converters">
        <UserControl.Resources>
            <converters:ItemCountToBooleanConverter x:Key="MyConverter" />
        </UserControl.Resources>
    </UserControl>
    

    和转换器:

    namespace My.Namespace.With.Converters {
        public class ItemCountToBooleanConverter : IValueConverter 
        {
    
            // implementation of IValueConverter here
            ...
        }
    }
    

    这是我自己写的,如有错误请见谅;)

    另外:确保您的 viewModel 实现了 INotifyPropertyChanged 接口,但我假设您已经知道这一点。

    【讨论】:

    • 酷,我还没有使用过 Converters,但我会调查一下。
    【解决方案2】:

    @cguedel 方法是完全有效的,但如果你不想使用转换器(为什么要多一个类),那么在你的视图模型中有另一个类型为 bool 的属性可能称为 ShouldExpand,为什么要说这么多,让我来给你看:

    class YourViewModel {
        public bool ShouldExpand {
            get {
                return _theCollectionYouPopulatedTheGridWith.Length() != 0;
                // or maybe use a flag, you get the idea !
            }
        }
    
        public void ButtonPressed() {
            // populate the grid with collection
            // NOW RAISE PROPERTY CHANGED EVENT FOR THE ShouldExpand property
        }
    }
    

    现在在您的视图中使用此绑定:

    <Expander IsExpanded="{Binding Path=ShouldExpand}" />
    

    正如我之前所说,其他解决方案很好,但我喜欢减少我的解决方案中的类数量。这只是另一种方式。

    【讨论】:

    • 我更喜欢这个 - 无论是那个还是你维护一个大型可重用转换器库
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-04
    • 1970-01-01
    相关资源
    最近更新 更多