【发布时间】:2018-12-25 11:06:21
【问题描述】:
如何使用 RelayCommand 将 2 个参数传递给命令。我需要将 COControls 作为参数(网格和窗口)传递。我完全意识到 Stack Overflow 上已经存在此类问题,但我正在努力根据自己的需要进行调整。
- 看看我的第一次尝试如下。这显然不起作用,因为 Relay 无法获得 2 个参数。
Xaml 代码:
<Button Name="StretchScreenBtn" Content="Stretch screen" DataContext=" {StaticResource CommandWindow}" Command="{Binding ResizeScreenCommand}"
Width="100" Height="50">
<Button.CommandParameter>
<MultiBinding Converter="{StaticResource CommandParamsConv}">
<Binding ElementName="ScreenGrid" />
<Binding RelativeSource="{RelativeSource AncestorType=Window}" />
</MultiBinding>
</Button.CommandParameter>
</Button>
来自 ViewModel 的命令代码:
private ICommand _ResizeScreenCommand;
public ICommand ResizeScreenCommand
{
get
{
if (_ResizeScreenCommand == null)
{
_ResizeScreenCommand = new RelayCommand(
(argument1, argument2) =>
{
Grid grid = argument1 as Grid;
Window window = argument2 as Window;
if ((int)grid.GetValue(Grid.ColumnSpanProperty) == 2)
{
grid.SetValue(Grid.ColumnSpanProperty, 1);
window.WindowStyle = WindowStyle.None;
}
else
{
grid.SetValue(Grid.ColumnSpanProperty, 2);
window.WindowStyle = WindowStyle.SingleBorderWindow;
}
}
);
}
return _ResizeScreenCommand;
}
}
还有 MultiValueConverter:
class CommandParamsConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
object[] parameters = values;
return parameters;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
- 我的第二次尝试遵循How to Passing multiple parameters RelayCommand? 的解决方案
因此,我在 ViewModel 中创建了具有两个属性 Grid 和 Window 类型的新类,然后尝试在 xaml 中将元素绑定到这些属性。但是在这种情况下,编译器会抱怨这些属性是非依赖的,不能被绑定。
请给我任何提示如何解决它?
下面是修改后的xaml代码:
<Button Name="StretchScreenBtn" Content="Stretch screen" DataContext="{StaticResource CommandWindow}" Command="{Binding ResizeScreenCommand}"
Width="100" Height="50">
<Button.CommandParameter>
<vm:StretchingModel Grid="{Binding ElementName=ScreenGrid}" Win="{Binding RelativeSource={RelativeSource AncestorType=Window}}" />
</Button.CommandParameter>
</Button>
以及 ViewModel 中的附加类:
class StretchingModel
{
public Grid Grid { get; set; }
public Window Win { get; set; }
}
【问题讨论】:
-
所以你想将控件绑定到命令(这是不受欢迎的,强烈不推荐)并且你已经知道问题标题的答案。我只会说使用 MVVM,不要将 Controls 绑定到任何东西。
-
是的,我知道,但我不会在代码隐藏中使用控件名称。我的意思是它们从 View 传递到 ViewModel,而 VieModel 将它们视为对象类型,然后将它们转换为适当的类型(网格和窗口)。不管怎样,Bijan,你能提出你的想法,你将如何进行这种绑定?
-
这个想法是标准的 MVVM,其中 VM 不知道 View。无论您需要在什么视图上使用绑定,肯定都有一个应该使用的虚拟机。为了可视化虚拟机,首先用于渲染视图的样式或模板都可以用于渲染绑定的虚拟机。
-
好的,我会尝试这样做。但是如果是 MVVM 中的对话框窗口呢?我需要使用 OpenFileDialog 所以我会在 View 中创建适当的类,然后使用 XAML 中 View 中创建的 OpenFileDialog 类来设置属性的值(如 Caption、Filter 等)并将其绑定到任何按钮命令运行窗口。然后我还需要将视图中的 FilePath 传递给 ViewModel 中的命令,该命令将处理文件打开以及如何执行这些操作?您是否曾经在 Xaml 中处理过对话框窗口。你能给我一些提示吗?
-
这篇文章可以帮助
OpenFileDialogstackoverflow.com/q/1619505/366064
标签: wpf mvvm command multibinding relaycommand