Search code examples
c#wpfxamlcommandparameter

New window as CommandParameter every time


I want a button to show app settings window like this:

<Window.Resources>
    <local:SettingsWindow x:Key="SettingsWnd"/>
</Window.Resources>
<Window.DataContext>
    <local:MyViewModel/>
</Window.DataContext>
<Button Command="{Binding ShowSettingsCommand}"
    CommandParameter="{DynamicResource SettingsWnd}"/>

The ViewModel kinda thing:

class MyViewModel : BindableBase
{
    public MyViewModel()
    {
        ShowSettingsCommand = new DelegateCommand<Window>(
                w => w.ShowDialog());
    }

    public ICommand ShowSettingsCommand
    {
        get;
        private set;
    }
}

The problem is that it only works one time because you can't reopen previously closed windows. And apparently, the XAML above does not make new instances to open like that.

Is there a way to pass new window as CommandParameter every time the command is called?


Solution

  • Does this converter solve your problem?

    class InstanceFactoryConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var type = value.GetType();
    
            return Activator.CreateInstance(type);
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
    

    ...

    <Window.Resources>
        <local:SettingsWindow x:Key="SettingsWnd"/>
        <local:InstanceFactoryConverter x:Key="InstanceFactoryConverter"/>
    </Window.Resources>
    

    ...

    <Button Command="{Binding ShowSettingsCommand}"
        CommandParameter="{Binding Source={StaticResource SettingsWnd}, Converter={StaticResource InstanceFactoryConverter}}"/>