【发布时间】:2011-01-13 19:55:35
【问题描述】:
这很难解释,但我会尽力而为。 我想要一个具有 3 个按钮的可重用控件,一个用于创建实体,另一个用于编辑,另一个用于删除,这是相关部分的缩写 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 按钮有一个 Command 依赖属性,您可以将命令绑定到该属性,因此创建我自己的可重用控件并公开 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>
【问题讨论】:
标签: c# .net wpf data-binding command