gpt4 book ai didi

c# - C#/MVVM : Enable/Disable Buttons based on another control's property

转载 作者:行者123 更新时间:2023-12-03 11:00:51 26 4
gpt4 key购买 nike

说我有一个选项卡控件,它显示各种类型的数据,例如EditorTabViewModelPreviewTabViewModel都继承自TabViewModel。实现类似于tutorial on MSDN

我想根据 Activity 选项卡启用按钮,无论是EditorTabViewModel还是PreviewTabViewModel。我该如何实现?

更新

public ICommand EditorCommand
{
get
{
if (_editorCommand == null) {
_editorCommand = new RelayCommand(() =>
{
MessageBox.Show("Editor");
}, () =>
{
var enabled = true;
var viewSource = CollectionViewSource.GetDefaultView(Tabs);
viewSource.CurrentChanged += (o, e) =>
{
if (viewSource.CurrentItem is EditorTabViewModel)
{
enabled = false;
}
};
return enabled;
});
}
return _editorCommand;
}
}

更新2
public ICommand PreviewCommand
{
get
{
if (_previewCommand == null) {
_previewCommand = new RelayCommand(() =>
{
MessageBox.Show("Preview");
}, () =>
{
var viewSource = CollectionViewSource.GetDefaultView(Tabs);
var enabled = viewSource.CurrentItem is EditorTabViewModel;
viewSource.CurrentChanged += (o, e) =>
{
CommandManager.InvalidateRequerySuggested();
};
return enabled;
});
}
return _previewCommand;
}
}

最佳答案

我建议您创建一个ICommand实现,该实现在包含2个选项卡控件的ICollectionView上构造。然后,该命令可以对集合 View 中的CurrentChanged事件使用react,以确定是否应启用它,并引发CanExecuteChanged事件以指示更改。

class MyCommand : ICommand
{
private bool _isEnabled = true;

public MyCommand(MyTopLevelViewModel viewModel)
{
var viewSource = CollectionViewSource.GetDefaultView(viewModel.Tabs);
viewSource.CurrentChanged += (o,e) =>
{
_isEnabled = (viewSource.CurrentItem is EditorTabViewModel); //or however you want to decide

if (this.CanExecuteChanged != null)
this.CanExecuteChanged(this, EventArgs.Empty);

};
}

public void Execute(object parameter) { /*...*/ }

public bool CanExecute(object parameter) { return _isEnabled; }

public event EventHandler CanExecuteChanged;
}

注意:您将需要在标签控件上设置 IsSyncronizedWithCurrentItem属性:
<TabControl IsSynchronizedWithCurrentItem="True" />

关于c# - C#/MVVM : Enable/Disable Buttons based on another control's property,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3878519/

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