我注意到一个奇怪的错误。当我将命令绑定到画布MouseLeftButtonDown事件时,它不会触发。我尝试调试并注意到它会触发,但仅在初始化期间。我猜这个症结在于约束力。这是代码:
<ItemsControl Grid.Row="1" ItemsSource="{Binding Polygons}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas>
<i:Interaction.Behaviors>
<behaviours:MouseBehaviour MouseX="{Binding MouseX, Mode=OneWayToSource}" MouseY="{Binding MouseY, Mode=OneWayToSource}" />
</i:Interaction.Behaviors>
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseLeftButtonDown">
<command:EventToCommand Command="{Binding SelectPointCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Canvas>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
/* some data template
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
命令实现:
public ICommand SelectPointCommand
{
get
{
if (!CanEdit)
return new RelayCommand(e => { });
ClickCounter++;
if (ClickCounter == 3)
{
ClickCounter = 0;
CanEdit = false;
}
return new RelayCommand(
() =>
{
Polygons.Add(new Polygon(ClickedPoints));
ClickedPoints.Clear();
});
}
}
我猜这里的问题是在MouseBehaviour中,但删除这段代码也没有用。
ps:我尝试设置画布背景属性,但它没有用。 以及将命令设置为此
SelectPointCommand = new RelayCommand(
() =>
{
System.Windows.MessageBox.Show("Test");
},
() => true);
修改 我试着调用这样的方法:
<Canvas Background="Transparent" MouseLeftButtonDown="UIElement_OnMouseLeftButtonDown">
</Canvas>
背后的代码:
private void UIElement_OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
((MainViewModel)DataContext).SelectPointCommand.Execute(e);
}
方法UIElement_OnMouseLeftButtonDown无论如何都不被调用; 将Canvas更改为StackPanel具有相同的结果。
答案 0 :(得分:0)
由于您没有发布所有代码,因此很难检查出错了什么。 CanEdit属性在其他一些地方有变化吗?什么是ClickCounter?
我认为问题出在SelectPointCommand的getter上。在创建绑定时,它只执行一次。我还将使用ICommand的CanExecute方法并在私有字段中存储getter的返回值。例如:
private ICommand _selectPointCommand;
ICommand SelectPointCommand
{
get
{
Console.WriteLine("This is executed once");
return _selectPointCommand;
}
set
{
if (_selectPointCommand != value)
{
_selectPointCommand = value;
OnPropertyChanged("SelectPointCommand");
}
}
}
在ViewModel的构造函数中:
SelectPointCommand = new RelayCommand(
(x) =>
{
Console.WriteLine("This is executed every click");
ClickCounter++;
if (ClickCounter == 3)
{
ClickCounter = 0;
CanEdit = false;
}
Polygons.Add(new Polygon(ClickedPoints));
ClickedPoints.Clear();
},
(x) => { return CanEdit; });
答案 1 :(得分:0)
好的伙计们,我修复了这个错误。问题出在这里:
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
将行的高度设置为&#34;自动&#34;意味着将其设置为零。所以画布并不存在!我这样离开了:
<RowDefinition/>
之后一切正常。