我是 winRT 的新手,并为此苦苦挣扎。
我创建了一个 DemoViewModel,我在其中声明了一个 DemoClickCommand,如下所示。该命令的类型为 DelegateCommand。
public DelegateCommand DemoClickCommand { get; private set; }
protected virtual void OnClickCommandExecuted(object parameter)
{
var obj = parameter;
}
protected virtual bool OnClickCommandCanExecute(object parameter)
{
return true;
}
public DemoViewModel()
{
this.DemoClickCommand = new DelegateCommand(this.OnClickCommandExecuted, this.OnClickCommandCanExecute);
}
我已将此命令绑定到表单上的一个按钮,该按钮本身可以正常工作,但在包含在使用数据模板的 listView 中时不起作用。
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
<!-- THIS BUTTON WORKS FINE-->
<Button Content="Button"
HorizontalAlignment="Left"
Height="143"
Margin="1354,424,0,0"
VerticalAlignment="Top"
Width="307"
Background="#FFC11A1A"
FontSize="36"
Command="{Binding DemoClickCommand, Mode=OneWay}" />
<!-- THIS LISTVIEW WHICH USES THE DATATEMPLATE WONT WORK -->
<ListView x:Name="lvDemoItems"
SelectionChanged="lvDemoItems_SelectionChanged"
Grid.Column="0"
Margin="0,140,0,0"
ItemTemplate="{StaticResource DemoTemplate}"
ItemsSource="{Binding DemoItems}"
SelectionMode="Single"
HorizontalAlignment="Left"
Width="904">
</ListView>
</Grid>
这是我的页面资源中定义的数据模板
<Page.Resources>
<DataTemplate x:Name="DemoTemplate">
<Grid Height="110"
Width="480"
Margin="10">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Border Background="{StaticResource ListViewItemPlaceholderBackgroundThemeBrush}"
Width="110"
Height="110">
<Image Source="{Binding ImageURI}"
Stretch="UniformToFill"
AutomationProperties.Name="{Binding Title}" />
</Border>
<StackPanel Grid.Column="1"
VerticalAlignment="Top"
Margin="10,0,0,0">
<TextBlock Text="{Binding Name}"
Style="{StaticResource TitleTextStyle}"
TextWrapping="NoWrap" />
<TextBlock Text="{Binding Description}"
Style="{StaticResource BodyTextStyle}"
MaxHeight="160" />
<Button Content="Edit"
BorderBrush="Black"
Background="Green"
Height="40"
Width="80"
Margin="0,20,0,0"
Command="{Binding DemoClickCommand, Mode=OneWay}"
CommandParameter="{Binding ID}" />
</StackPanel>
</Grid>
</DataTemplate>
</Page.Resources>
我想我需要使用附加的依赖属性,但不知道如何实现它。
这是我到目前为止所拥有的,但我不知道如何让它发挥作用。你能帮忙解释一下吗?谢谢
public ICommand DemoClickCommand { get; private set; }
public static readonly DependencyProperty DemoClickCommand =
DependencyProperty.RegisterAttached("DemoClickCommand", typeof(ICommand), typeof(Button), new PropertyMetadata(null, OnItemCommandPropertyChanged));
private static void OnClickCommandPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
ICommand command = e.NewValue as ICommand;
}