我的问题是没有连线DependencyProperties
在UserControl
。这不是问题。当我将UserControl
中的按钮绑定到UserControl
的DependencyProperty
时,调用TargetCommand
,当我在UserControl
上设置DataContext
时,绑定中断。我尝试过使用FindAncestor
,当然还有ElementName
,但它们仅在UserControl
上没有DataContext
时起作用。如何:当UserControl具有DataContext时绑定到UserControl的DependencyProperty?
有没有办法解决这个问题?
例如:
主窗口
<Window xmlns:UserControls="clr-namespace:SomeNameSpace">
<Grid>
<UserControls:MyUserControl
TargetCommand="{Binding PathToCommand}"
DataContext="{Binding PathToSomeModel}" />
的MyUserControl代码后面
public partial class MyUserControl : UserControl
{
public static readonly DependencyProperty TargetCommandProperty =
DependencyProperty.Register("TargetCommand", typeof(ICommand), typeof(MyUserControl));
public ICommand TargetCommand
{
get { return (ICommand)GetValue(TargetCommandProperty); }
set { SetValue(TargetCommandProperty, value); }
}
的MyUserControl - 的Xaml
<UserControl x:Name="root">
<Button Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=TargetCommand}" />
<Button Command="{Binding Path=TargetCommand, ElementName=root}" />
的的RelativeSource和方法具的ElementName只要未在MainWindow中的MyUserControl上设置DataContext,MyUserControl中绑定的ds都会正确连接。一旦设置了DataContext,就不会工作。
有没有办法在MyUserControl上设置DataContext,并仍然将DependencyProperty绑定到TargetCommand?
不错......我忽略了这一点。谢谢 – Nicholas 2011-02-17 19:42:20