【发布时间】:2017-04-14 19:32:41
【问题描述】:
我是 MVVM 和 wpf 的新手...
总结形式的问题 - 如何使用 wpf 和 MVVM 控制控件的可见性。它也应该有零代码。
实际场景-我有多个用户控制面板...说UCPanel1,UCPanel2,UCPnale3...直到6
- 我将这些用户控件导入到一个主用户控件中......比如说 UCMain
这是在顶部有按钮的堆栈面板......就像菜单一样。
- 现在要求非常简单......在按钮1上单击-我应该能够看到隐藏的UCPanel1和其余面板,单击按钮2-我应该能够看到隐藏的UCPanel2和其余面板......等等
- 我使用后面的代码成功地实现了这一点。但要求是实现这样一种方式,即在后面的代码中应该有尽可能少的代码。
那么我的 XAML 和视图模型是什么样的呢?
我无法在 viewmodel 中访问 UCPanel1 的扩展对象..
在 MainPanel XAML...
<Button
Style="{StaticResource StackPanelButtonStyle}"
Command="{Binding openMessageCommand}" >
<!--Click="BtnMessege_OnClick" >-->
<TextBlock
Text="Messaging"
Style="{StaticResource StackPanelButtonTextStyle}">
</TextBlock>
</Button>
<Button
Style="{StaticResource StackPanelButtonStyle}"
Command="{Binding openProductsCommand}">
<!--Click="BtnProducts_OnClick">-->
<TextBlock
Text="Products"
Style="{StaticResource StackPanelButtonTextStyle}" ></TextBlock>
</Button>
<local:StackPanelMessaging
Grid.Row="2"
Visibility="{Binding Panel1Visiblity}"></local:StackPanelMessaging>
<local:WrapPanelProducts
Grid.Row="2"
Visibility="{Binding Panel2Visiblity}" ></local:WrapPanelProducts>
在主视图模型中...
private Visibility _panel1Visiblity= Visibility.Visible;
private Visibility _panel2Visiblity= Visibility.Hidden;
public Visibility Panel1Visiblity
{
get { return _panel1Visiblity; }
set
{
if (_panel1Visiblity != value)
{
_panel1Visiblity = value;
OnPropertyChanged("Panel1Visiblity");
}
}
}
public Visibility Panel2Visiblity
{
get { return _panel2Visiblity; }
set
{
if (_panel2Visiblity != value)
{
_panel2Visiblity = value;
OnPropertyChanged("Panel2Visiblity");
}
}
}
private void OpenStackMessagePanel()
{
Panel1Visiblity = Visibility.Visible;
Panel2Visiblity = Visibility.Hidden;
}
private bool canExecuteMethod1()
{
return true;
}
private void OpenWrapProductsPanel()
{
Panel2Visiblity = Visibility.Visible;
Panel1Visiblity = Visibility.Hidden;
}
private bool canExecuteMethod2()
{
return true;
}
public ICommand openMessageCommand
{
get
{
if (_openMessageCommand == null)
{
_openMessageCommand = new DelegateCommand(OpenStackMessagePanel, canExecuteMethod1, true);
}
return _openMessageCommand;
}
}
public ICommand openProductsCommand
{
get
{
if (_openProductsCommand == null)
{
_openProductsCommand = new DelegateCommand(OpenWrapProductsPanel, canExecuteMethod2, true);
}
return _openProductsCommand;
}
}
另外我觉得写这么多代码真的值得吗?还是我应该更喜欢只剩下 10 行的代码....
【问题讨论】:
-
这通常使用视图模型中的命令和可见性属性来完成,或者如果这纯粹是 UI,则将触发器添加到按钮以运行故事板,从而为面板上的可见性属性设置动画。
-
感谢您的回复。是的,我也这样做了,但不知道我错在哪里,单击按钮后面板仍然没有改变。有关详细信息,请参阅编辑后的问题...
-
不确定您是怎么知道的 - 您的面板中没有任何内容。添加断点并首先证明您的视图模型。
标签: wpf xaml mvvm data-binding viewmodel