【发布时间】:2015-07-06 16:01:56
【问题描述】:
我有一个 MVVM 应用程序,部分功能是在我的视图模型中发出命令。绑定到命令的控件恰好位于 DataGrid 的行中。这是一些 XAML:
<DataGridTemplateColumn Width="25">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<!--<base:DeleteButton HorizontalAlignment="Center" ToolTip="Delete Polygon"
Visibility="{Binding Path=CanDeleteFromUI, Mode=OneWay, Converter={StaticResource BooleanToVisibilityConverter}}"
Command="{Binding Path=DataContext.DeletePolygonCommand, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" CommandParameter="{Binding}"/>-->
<CheckBox Template="{StaticResource RemoveXButtonTemplate}" Margin="0,0,3,0" HorizontalAlignment="Center" ToolTip="Delete Polygon" Cursor="Hand" Visibility="{Binding Path=CanDeleteFromUI, Mode=OneWay, Converter={StaticResource BooleanToVisibilityConverter}}"
Command="{Binding Path=DataContext.DeletePolygonCommand, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"
CommandParameter="{Binding}" >
</CheckBox>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
注意:由于各种原因,“按钮”实际上是一个复选框。
这在编码时工作得很好。请注意,有一个注释掉的用户控件,我无法正常工作,但“真实”复选框工作正常。
这是用户控件的 XAML:
<UserControl x:Class="Athena.Infrastructure.DeleteButton"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d" >
<Grid>
<CheckBox Command="{Binding Path=Command}" CommandParameter="{Binding Path=CommandParameter}" Cursor="Hand">
<CheckBox.Template>
<ControlTemplate>
<Border Width="14" Height="14" Background="#00000000" Margin="2,0,2,0">
....
....
</ControlTemplate>
</CheckBox.Template>
</CheckBox>
</Grid>
</UserControl>
我没有包含控件模板的所有 XAML,因为一切都显示得很好。
下面是代码:
public partial class DeleteButton : UserControl
{
public DeleteButton()
{
InitializeComponent();
}
public static readonly DependencyProperty CommandProperty = DependencyProperty.Register("Command", typeof(ICommand), typeof(DeleteButton));
public ICommand Command
{
get { return (ICommand) GetValue(CommandProperty); }
set{SetValue(CommandProperty, value);}
}
public static readonly DependencyProperty CommandParameterProperty = DependencyProperty.Register("CommandParameter", typeof(object), typeof(DeleteButton));
public object CommandParameter
{
get { return (object) GetValue(CommandParameterProperty); }
set { SetValue(CommandParameterProperty, value); }
}
}
我没有展示我的 VM 代码,但它包含常用的 3 种方法,Command、CanExecute 和 Method。当我使用复选框时,命令执行一次(以初始化方法),然后当我单击复选框时方法会触发。
当我使用用户控件而不是普通复选框时,我的 VM 中的命令会按预期触发一次。此后,该方法根本不会触发。
使用用户控件而不是本机控件似乎很常见,对吧?我无法弄清楚为什么我的 VM 方法不会使用用户控件触发。
有人可以帮我解释一下吗?非常感谢...
【问题讨论】:
标签: c# xaml mvvm user-controls