每次

时间:2015-08-11 19:37:16

标签: c# wpf xaml commandparameter

我想要一个按钮来显示应用设置窗口,如下所示:

<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;
    }
}

问题是它只能运行一次,因为你无法重新打开以前关闭的窗口。显然,上面的XAML并没有像这样打开新的实例。

每次调用命令时,有没有办法将新窗口作为CommandParameter传递?

1 个答案:

答案 0 :(得分:2)

此转换器能否解决您的问题?

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