gpt4 book ai didi

c# - 根据 MainViewModel 中的状态启用/禁用不同 View 上的控件的最佳方法

转载 作者:行者123 更新时间:2023-12-03 10:36:35 24 4
gpt4 key购买 nike

我有一个正在开发的应用程序。它可以处于两种状态(已连接和已断开)。我的 MainViewModel 中有一个 bool 属性,用于跟踪当前状态。

我的应用程序中有许多其他 View (和 ViewModel)。当应用程序进入断开状态时,我需要在每个 View 中禁用多个控件(不是全部)。当应用程序处于连接状态时,显然我需要启用这些相同的控件。

我想知道什么是实现这一目标的好方法?

最佳答案

我猜你的 MainViewModel 只有一个实例.

所以通过 公开这个唯一的实例静态属性 ,甚至将其设为 单例 .

这样,您可以轻松地在 View 之间共享您的连接状态。

using System.ComponentModel;

namespace WpfMagic
{
public class MainViewModel : INotifyPropertyChanged
{
private static readonly MainViewModel instance = new MainViewModel();

public static MainViewModel Instance { get { return instance; } }

private bool isConnected;
public bool IsConnected
{
get { return isConnected; }
set
{
if (value != isConnected)
{
isConnected = value;
PropertyChanged(this, new PropertyChangedEventArgs("IsConnected"));
}
}
}

private MainViewModel()
{
}

public event PropertyChangedEventHandler PropertyChanged = delegate { };
}
}

棘手的部分是静态绑定(bind),但除此之外很简单:

您的第一个 View :
<Button IsEnabled="{Binding Path=(local:MainViewModel.Instance).IsConnected}">Send Spams</Button>

另一个:
<Button IsEnabled="{Binding Path=(local:MainViewModel.Instance).IsConnected}">DDOS SO</Button>

最后一个:
<Button IsEnabled="{Binding Path=(local:MainViewModel.Instance).IsConnected}">Open Lol Cats Videos</Button>

要测试它,您可以使用 CheckBox在另一种观点中:
<CheckBox IsChecked="{Binding Path=(local:MainViewModel.Instance).IsConnected}">Is Connected?</CheckBox>

关于c# - 根据 MainViewModel 中的状态启用/禁用不同 View 上的控件的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25273383/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com