New window as CommandParameter 每次

New window as CommandParameter every time

我想要一个按钮来显示应用程序设置 window,如下所示:

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

ViewModel 有点东西:

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

    public ICommand ShowSettingsCommand
    {
        get;
        private set;
    }
}

问题是它只能工作一次,因为您无法重新打开之前关闭的 windows。显然,上面的 XAML 不会让新实例像那样打开。

有没有办法在每次调用命令时将新的 window 作为 CommandParameter 传递?

这个转换器能解决您的问题吗?

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}}"/>