C# 每次都将新窗口作为CommandParameter
我想要一个按钮来显示应用程序设置窗口,如下所示:C# 每次都将新窗口作为CommandParameter,c#,wpf,xaml,commandparameter,C#,Wpf,Xaml,Commandparameter,我想要一个按钮来显示应用程序设置窗口,如下所示: <Window.Resources> <local:SettingsWindow x:Key="SettingsWnd"/> </Window.Resources> <Window.DataContext> <local:MyViewModel/> </Window.DataContext> <Button Command="{Binding ShowS
<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;
}
}
类MyViewModel:BindableBase
{
公共MyViewModel()
{
ShowSettingsCommand=新的DelegateCommand(
w=>w.ShowDialog());
}
公共ICommand显示设置命令
{
得到;
私人设置;
}
}
问题是它只工作一次,因为您无法重新打开以前关闭的窗口。显然,上面的XAML并没有让新实例像那样打开
是否有办法在每次调用命令时将新窗口作为
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();
}
}
您正在使用一个资源,完成后将其关闭。您可以在调用ShowDialog
后重新分配资源给新资源。我正在尝试不引用代码中的设置窗口类型。“重新分配资源”会让我这么做,不是吗?是的,但是ShowDialog
调用窗口上的Close
,这基本上会破坏您在XAML中创建的资源。您必须在某个地方创建一个新对话框,或者不使用资源并在命令中完全执行,或者在显示对话框后重新创建对话框以供下次使用。抱歉,这还不是问题的答案。我希望避免在代码中引入依赖项。也许我应该弄清楚这一点。是的,这看起来像是我自己使用CommandParameter=“{x:Type local:SettingsWindow}”和(Activator.CreateInstance(w)作为窗口)。在DelegateCommand
中的ShowDialog()
。如果几天后没有其他选择,我将不得不接受这个解决方案。谢谢
<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}}"/>