Почему не работает переключение состояний?
Ситуация: я создаю меню в котором есть действия, одно из действий должно переключить frame
на следующий кадр/состояние.
Проблема: Оно не работает, хотя DataContext
подключён и нету ошибок привязки.
Минимальный воспроизводимый пример: В App.xaml
удаляем StartupUri
( вроде так...), затем в App.xaml.cs
пишем код:
public partial class App : Application
{
private static Page one = new Page1();
private static Page two = new Page2();
Tabs tabs = new Tabs() { One = one, Two = two, Current = one};
protected override void OnStartup(StartupEventArgs args)
{
base.OnStartup(args);
one.DataContext = tabs;
two.DataContext = tabs;
new MainWindow() { DataContext = tabs}.Show();
}
}
Создать Tab.cs
и прописать вот это:
Минутка пояснения: этот код содержит страницы и команду открытия. Кнопка или что-то другое, вызывает команду с параметром страницы. Здесь RelayCommand
для работы)
public class RelayCommand : ICommand
{
private Action<object> execute;
private Func<object, bool> canExecute;
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public RelayCommand(Action<object> execute, Func<object, bool> canExecute = null)
{
this.execute = execute;
this.canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
return this.canExecute == null || this.canExecute(parameter);
}
public void Execute(object parameter)
{
this.execute(parameter);
}
}
public class Tabs : INotifyPropertyChanged
{
private Page _One;
private Page _Two;
public Page One
{
get => _One;
set
{
_One = value;
OnPropertyChanged("selected");
}
}
public Page Two
{
get => _Two;
set
{
_Two = value;
OnPropertyChanged("selected");
}
}
private Page _Current;
public Page Current
{
get => _Current;
set
{
_Current = value;
OnPropertyChanged("selected");
}
}
public ICommand Open => new RelayCommand(obj => Current = (Page)obj);
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged([CallerMemberName] string prop = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(prop));
}
}
Создаём страницы Page1
и Page2
, в первой создаём кнопку:
<Button Content="1" Margin="10" FontSize="50" Command="{Binding Open}" CommandParameter="{Binding Two}"/>
Во второй:
<Button Content="2" Margin="10" FontSize="50" Command="{Binding Open}" CommandParameter="{Binding One}"/>
При запуске ничего не происходит.
Может я что-то опускаю?