如何在mvvm的矩形命令上使用多重绑定?
问题描述:
我得到了以下矩形如何在mvvm的矩形命令上使用多重绑定?
<Rectangle
Width="{Binding Width}"
Height="{Binding Length}"
Tag="{Binding Id}"
Name="rectangleDrawnMachine">
<i:Interaction.Triggers>
<i:EventTrigger
EventName="MouseDown">
<cmd:EventToCommand
Command="{Binding Main.UpdateSelectedMachine, Mode=OneWay, Source={StaticResource Locator}}"
PassEventArgsToCommand="True"
CommandParameter="{Binding ElementName=rectangleDrawnMachine}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</Rectangle>
该矩形被绑定到其在一个以上的ItemsControl声明的模型。该文件结构是如下所示:
<Grid>
<ItemsControl ItemsSource="{Binding AllMachines}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas Name="canvasDrawnMachines" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<Rectangle Name="rectangleDrawnMachine"/>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
现在我UpdateSelectedMachine -command需要矩形的至少三个属性:
- 位置X
- 位置Y
- ID /标签
使用CommandParameter o如果矩形本身,我的命令会得到很多关于矩形的信息(比如需要的标签)。但它没有获得关于画布的(X-& Y-)位置的必要信息。
所以我的问题是:如何在我的矩形命令上使用多重绑定?以及如何转移画布的位置?
答
您不能使用命令参数传递多个值。
为了做到这一点,你必须使用多重绑定。
<cmd:EventToCommand
Command="{Binding Main.UpdateSelectedMachine, Mode=OneWay, Source={StaticResource Locator}}"
PassEventArgsToCommand="True">
<cmd:EventToCommand.CommandParameter>
<MultiBinding Converter="{StaticResource YourConverter}">
<Binding Path="Canvas.Left" ElementName="canvasDrawnMachines"/>
<Binding Path="Canvas.Top" ElementName="canvasDrawnMachines"/>
<Binding Path="Tag" ElementName="canvasDrawnMachines"/>
</MultiBinding>
</cmd:EventToCommand.CommandParameter>
你的转换器:
public class YourConverter : IMultiValueConverter
{
public object Convert(object[] values, ...)
{
return values.Clone();
}
}
然后,执行命令的逻辑:
public void OnExecute(object parameter)
{
var values = (object[])parameter;
var left = (double)values[0];
var top = (double)values[1];
var tag = values[2];
}
答
你可以得到要传递的命令参数的命令,像这样的Rectangle
的Canvas.Left
和Canvas.Top
附加属性的值:
double x = Canvas.GetLeft(rectangle);
double y = Canvas.GetTop(rectangle);
你知道如何得到这个职位在XAML方式?
使用MultiBinding
与转换器并绑定到Canvas.Left
和Canvas.Top
属性:
<MultiBinding Converter="{StaticResource converter}">
<Binding Path="(Canvas.Left)" ElementName="canvasDrawnMachines"/>
<Binding Path="(Canvas.Top)" ElementName="canvasDrawnMachines"/>
<Binding Path="Tag" ElementName="canvasDrawnMachines"/>
</MultiBinding>
谢谢您的回答。多重绑定方式工作得很好。问题是画布的矩形位置不能传递正确的值。它说'没有定义'。也许是因为我的数据模板有多个矩形? – Chpo7234
这不是多个矩形的问题。你可以尽可能多地拥有它。我已经更新了答案中的绑定。 – Parag
感谢您的更新。问题例如Canvas.Top返回我{DependencyProperty.UnsetValue}。代码' '没有问题 –
Chpo7234