这是最好的解决方案:
<Grid DataContext="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}}" >
<Button Content="{Binding ButtonContent}" Command="{Binding ClickHereCommand}" Height="25" Width="90"></Button>
</Grid>
其他解决方案:
你忘记设置了数据上下文 to 用户控制1.
public UserControl1()
{
InitializeComponent();
ClickHereCommand = new RoutedCommand();
CommandBindings.Add(new CommandBinding(ClickHereCommand, ClickHereExecuted));
ButtonContent = "Click Here";
this.DataContext = this;
}
之后你必须删除用户控制1网格中的数据上下文。
This:
<Grid DataContext="{Binding ElementName=root}" >
<Button Content="{Binding ButtonContent}" Command="{Binding ClickHereCommand}" Height="25" Width="90"></Button>
</Grid>
你必须更改为:
<Grid>
<Button Content="{Binding ButtonContent}" Command="{Binding ClickHereCommand}" Height="25" Width="90"></Button>
</Grid>
UserControl 中未设置 DataContext 的解决方案:
您必须将 ButtonContent 和 ClickHereCommand 更改为 DependencyProperty。
public string ButtonContent
{
get { return (string)GetValue(ButtonContentProperty); }
set { SetValue(ButtonContentProperty, value); }
}
public static readonly DependencyProperty ButtonContentProperty =
DependencyProperty.Register("ButtonContent", typeof(string), typeof(UserControl1), new UIPropertyMetadata(string.Empty));
public RoutedCommand ClickHereCommand
{
get { return (RoutedCommand)GetValue(ClickHereCommandProperty); }
set { SetValue(ClickHereCommandProperty, value); }
}
public static readonly DependencyProperty ClickHereCommandProperty =
DependencyProperty.Register("ClickHereCommand", typeof(RoutedCommand), typeof(UserControl1), new UIPropertyMetadata(null));
并在演员UserControl1
:
public UserControl1()
{
InitializeComponent();
ClickHereCommand = new RoutedCommand();
CommandBindings.Add(new CommandBinding(ClickHereCommand, ClickHereExecuted));
ButtonContent = "Click Here";
//this.DataContext = this;
}