如何让按钮的Click事件操纵MVVM中的另一个控件

时间:2013-05-30 18:27:02

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

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

例如:

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

想法?

2 个答案:

答案 0 :(得分:2)

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

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

然后在窗口或usercontrol中:

<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接口,但我假设你已经知道了。

答案 1 :(得分: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}" />

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