虽然有点难以解释,但我会尽力。我想要一个可重复使用的控件,其中包含三个按钮,一个用于创建实体,另一个用于编辑,第三个用于删除。以下是相关部分的缩写XAML。
--
<!-- ActionButtons.xaml -->
<StackPanel Orientation="Horizontal" HorizontalAlignment="Left" VerticalAlignment="Top">
<Button Name="btnNew" Content="New" Command="{Binding Path=NewCommand}" />
<Button Name="btnEdit" Content="Edit" Command="{Binding Path=EditCommand, Mode=OneWay}" />
<Button Name="btnDelete" Content="Delete" Command="{Binding Path=DeleteCommand, Mode=OneWay}" />
</StackPanel>
接着,在代码的后台,我有dpprops的声明:
// ActionButtons.xaml.cs
public uscActionButtons()
{
InitializeComponent();
this.DataContext = this;
}
public ICommand NewCommand
{
get { return (ICommand)GetValue(NewCommandProperty); }
set { SetValue(NewCommandProperty, value); }
}
// Using a DependencyProperty as the backing store for NewCommand. This enables animation, styling, binding, etc...
public static readonly DependencyProperty NewCommandProperty =
DependencyProperty.Register("NewCommand", typeof(ICommand), typeof(uscActionButtons), new UIPropertyMetadata(null, new PropertyChangedCallback(OnCommandChanged)));
我想将NewCommand属性绑定到另一个控件中的特定实现。示例用法如下:
<!-- SomeControl.xaml -->
<common:uscActionButtons Grid.Row="0" HorizontalAlignment="Left"
NewCommand="{Binding NewItemCommand}"
/>
并且
// SomeControlViewModel.cs
// Note: SomeControlViewModel IS in the DataContext of SomeControl.
public ICommand NewItemCommand
{
get
{
if (mNewItemCommand == null)
{
mNewItemCommand = new RelayCommand(x => this.CreateItem());
}
return mNewItemGroupCommand;
}
}
问题在于可重用控件(ActionButtons)无法看到NewItemCommand。如果使用简单按钮,则可以正常看到。似乎问题在于这个“链接”绑定。但是我知道这是可能的,WPF按钮具有一个命令依赖属性,您可以将其绑定到自己的命令,因此创建自己的可重用控件并公开ICommand依赖属性不应该那么难。
有什么想法吗?
谢谢
编辑:这是解决方案,我所要做的就是使用RelativeSource和FindAncestor。
<StackPanel Orientation="Horizontal" HorizontalAlignment="Left" VerticalAlignment="Top">
<Button Name="btnNew" Content="New" Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=my:uscActionButtons}, Path=NewCommand, Mode=OneWay}" />
<Button Name="btnEdit" Content="Edit" Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=my:uscActionButtons}, Path=EditCommand, Mode=OneWay}" />
<Button Name="btnDelete" Content="Delete" Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=my:uscActionButtons}, Path=DeleteCommand, Mode=OneWay}" />
</StackPanel>