答案是依赖属性。我也有同样的问题。
首先,如果您没有涉及 DataTemplate,则解决方案很简单:
(this.Content as FrameworkElement).DataContext = this;
您可以在其构造函数中将 UserControl 的 DataContext 设置为其后面的代码。
如果您计划在 DataTemplate 中使用您的命令,您还需要一个 DependecyProperty。
Example:
<DataTemplate>
<Button Command="{Binding DataContext.MyCommand, ElementName=ParentName}">
</DataTemplate>
为了支持它,您为该命令创建一个依赖属性:
public ICommand MyCommand
{
get { return (ICommand)GetValue(MyCommandProperty); }
set { SetValue(MyCommandProperty, value); }
}
// Using a DependencyProperty as the backing store for MyCommand. This enables animation, styling, binding, etc...
public static readonly DependencyProperty MyCommandProperty =
DependencyProperty.Register("MyCommand", typeof(ICommand), typeof(ownerclass), new PropertyMetadata(0));
因此,现在,当您使用用户控件时,您将拥有一个 MyCommand 属性,只要模板父级与您提供的匹配,并且参数绑定到该实际项目,您就可以将其绑定到 ViewModel 中的任何命令。控制是其中的一部分。
<usercontrols:button MyCommand="{Binding MyCommandFromViewModel}" CommandParameter="{Binding}"/>
简单的例子:
用户控制代码隐藏
public sealed partial class ListviewUserControl : UserControl
{
public ListviewUserControl()
{
this.InitializeComponent();
(this.Content as FrameworkElement).DataContext = this;
}
public ICommand ButtonCommand
{
get { return (ICommand)GetValue(ButtonCommandProperty); }
set { SetValue(ButtonCommandProperty, value); }
}
// Using a DependencyProperty as the backing store for ButtonCommand. This enables animation, styling, binding, etc...
public static readonly DependencyProperty ButtonCommandProperty =
DependencyProperty.Register("ButtonCommand", typeof(ICommand), typeof(ListviewUserControl), new PropertyMetadata(null));
public ObservableCollection<Item> ItemsSource
{
get { return (ObservableCollection<Item>)GetValue(ItemsSourceProperty); }
set { SetValue(ItemsSourceProperty, value); }
}
// Using a DependencyProperty as the backing store for ItemsSource. This enables animation, styling, binding, etc...
public static readonly DependencyProperty ItemsSourceProperty =
DependencyProperty.Register("ItemsSource", typeof(ObservableCollection<Item>), typeof(ListviewUserControl), new PropertyMetadata(new ObservableCollection<Item>()));
}
用户控制Xaml:
<Grid>
<ListView ItemsSource="{Binding ItemSource}" x:Name="ListView">
<ListView.ItemTemplate>
<DataTemplate>
<!--some item related content-->
<AppBarButton Icon="Delete" Command="{Binding ButtonCommand, ElementName=ListView}" CommandParameter="{Binding}"/>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
Page.xaml 中的用法:
<Controls:ListviewUserControl ItemsSource="{Binding ViewModelsItemsList}" ButtonCommand="{Binding ViewModelsCommand}"/>