gpt4 book ai didi

c# - 每次都将新窗口作为 CommandParameter

转载 作者:太空宇宙 更新时间:2023-11-03 10:25:01 28 4
gpt4 key购买 nike

我想要一个按钮来显示这样的应用程序设置窗口:

<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 传递?

最佳答案

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

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

关于c# - 每次都将新窗口作为 CommandParameter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31950480/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com