wpf mvvm 显示隐藏按钮
时间: 2023-08-18 22:11:00 浏览: 130
可以通过绑定按钮的可见性属性来实现在WPF MVVM中的显示和隐藏按钮。
首先,在ViewModel中创建一个布尔类型的属性来控制按钮的可见性。例如:
```csharp
private bool _isButtonVisible;
public bool IsButtonVisible
{
get { return _isButtonVisible; }
set
{
_isButtonVisible = value;
OnPropertyChanged(nameof(IsButtonVisible));
}
}
```
然后,在View中使用DataTrigger来根据ViewModel中的属性值来设置按钮的可见性。例如:
```xaml
<Button Content="按钮" Width="100" Height="30">
<Button.Style>
<Style TargetType="Button">
<Setter Property="Visibility" Value="Collapsed"/>
<Style.Triggers>
<DataTrigger Binding="{Binding IsButtonVisible}" Value="True">
<Setter Property="Visibility" Value="Visible"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
```
这样,当ViewModel中的IsButtonVisible为True时,按钮将可见;当IsButtonVisible为False时,按钮将隐藏。
注意,需要将View的DataContext设置为ViewModel的实例,以便实现数据绑定。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)