我有一个用户控件,它为该控件定义了一个ItemsControl和一个ItemTemplate,即:
<ItemsControl Name="ItemsControl">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Name="SelectionButton" Content="MyButton"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
在代码后面,我指定了一个依赖属性,使我能够绑定ItemsControl的ItemsSource属性,即:
public static readonly DependencyProperty ButtonSourceProperty = DependencyProperty.Register(
"ButtonSource", typeof(IEnumerable), typeof(MyControl),
new PropertyMetadata(null, new PropertyChangedCallback(OnButtonSourceChanged)));
public IEnumerable ButtonSource
{
get { return (IEnumerable)GetValue(ButtonSourceProperty); }
set { SetValue(ButtonSourceProperty, value); }
}
private static void OnButtonSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var buttonSelectionControl = (ButtonSelectionControl)d;
buttonSelectionControl.ItemsControl.ItemsSource = (IEnumerable)e.NewValue;
}
public static void SetButtonSource(DependencyObject obj, IEnumerable enumerable)
{
obj.SetValue(ButtonSourceProperty, enumerable);
}
public static IEnumerable GetButtonSource(DependencyObject obj)
{
return (IEnumerable)obj.GetValue(ButtonSourceProperty);
}
这样,在XAML中,我可以设置MyControl的源如下:
<local:MyControl ButtonSource={Binding MyCollection} \>
这样可以工作,但是我如何在MyControl中定义一个依赖属性,以指定要绑定到MyCollection中的命令?目前我在XAML中声明了以下内容来进行命令绑定。
Command="{Binding DataContext.MyCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}"
CommandParameter="{Binding .}"
我该如何将此抽象化,以便我可以在XAML中绑定到要绑定的项命令,类似于以下内容:
<local:MyControl ButtonSource={Binding MyCollection}
ButtonCommand={Binding MyCommand} \>
指针赞赏。