用户控件中的 WPF 命令绑定不起作用

WPF command bindings in user controls not working

我已经非常努力地通过自己搜索网络和遵循示例来找到解决方案,但到目前为止我尝试的一切都失败了。我知道我对 WPF 的糟糕体验让我错过了一些巨大而愚蠢的东西,但事实上我被困住了。 如对象中所写,我有一个包含 RadioButton 的自定义 UserControl。我想通过我的 UserControl 的 DependencyProperty 'expose' RadioButtonCommand 外部。 UserControl(名为 'ImageRadioButton')的 .xaml 如下:

<UserControl x:Class="WpfSinergoHMIControls.Controlli.ImageRadioButton"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"                           
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800">

    <UserControl.Resources>

    </UserControl.Resources>

    <Grid>
        <Grid>
            <RadioButton Command="{Binding SomeCommand, ElementName=me}"  Name="button1" Foreground="White">

            </RadioButton>
        </Grid>   
    </Grid>
</UserControl>

UserControl 程序文件中的依赖关系 属性 如下:

public static readonly DependencyProperty SomeCommandProperty =
DependencyProperty.Register(
   "SomeCommand",
   typeof(ICommand),
   typeof(ImageRadioButton),
   new UIPropertyMetadata(null));

public ICommand SomeCommand
{
  get { return (ICommand)GetValue(SomeCommandProperty); }
  set { SetValue(SomeCommandProperty, value); }
}

最后,我在使用我的 UserControl 的应用程序中声明了一个实例:

<Controlli:ImageRadioButton x:Name="btnAutomatic" GroupName="MainMenu" SomeCommand="{Binding DataContext.NavigateAutomaticCommand, ElementName=MainViewObj}" HorizontalAlignment="Left" Height="60" VerticalAlignment="Bottom" Width="140" Canvas.Left="1373" Canvas.Top="5" Margin="6,0,0,5" IsChecked="True"/>

毫无价值地说这不起作用(没有调用命令)。我知道我遗漏了一些愚蠢的东西,但经过很多 trials/searching 我仍然找不到解决方案。 谢谢!

您在命令绑定中引用了元素 me,但您没有在任何地方分配该名称,这意味着在运行时无法找到绑定源(您的 UserControl)。

Command="{Binding SomeCommand, ElementName=me}"

如果您在 UserControl 上设置名称,一切都会按预期工作(至少对我而言)。

<UserControl x:Class="WpfSinergoHMIControls.Controlli.ImageRadioButton"
             ...
             x:Name="me">