[英]How do I have the Click event of a button manipulate another control in MVVM
我正在使用WPF(4.5)和Caliburn.Micro。 我试图了解如何在我的视图中操作“事件”操纵我的视图中的其他控件。
例如:
我的视图有一个Expander控件,一个Button和一个GridView。 GridView位于Expander中。 当用户单击该按钮时,它会调用VM中的方法,该方法使用BindableCollection <>填充gridview。 我想要发生的是当该集合有多于1个项目时我想自动扩展Expander Control。
想法?
您可以绑定到集合中的项目数:
<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接口,但我假设您已经知道了。
@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}" />
正如我之前所说,其他解决方案很好,但我想减少我的解决方案中的类数。 这只是另一种方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.