【问题标题】:WPF command bindings in user controls not working用户控件中的 WPF 命令绑定不起作用
【发布时间】:2021-02-09 14:38:28
【问题描述】:

我已经非常努力地通过自己搜索网络并遵循示例来找到解决方案,但到目前为止我所尝试的一切都失败了。我知道我对 WPF 的糟糕体验让我错过了一些巨大而愚蠢的东西,但事实上我被困住了。 如对象中所写,我有一个自定义 UserControl,其中包含 RadioButton。我想通过我的 UserControl 的 DependencyProperty 将RadioButton 的Command '公开'到外面。 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"/>

不用说这不起作用(没有调用命令)。我知道我缺少一些愚蠢的东西,但是经过大量试验/搜索后,我仍然找不到解决方案。 谢谢!

【问题讨论】:

  • 您应该在 UserControl 上添加 x:Name="me"。

标签: c# wpf xaml data-binding


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-09
    • 1970-01-01
    • 2011-08-11
    相关资源
    最近更新 更多