繁体   English   中英

相对来源从未调用过

[英]RelativeSource never called

我想将后面代码中的命令绑定到UserControl.Resources用户控制按钮( ICommand

所以我用RelativeSource写了一段代码。 但它没有用。

我尝试使用转换器进行调试来解决这个问题。

但即使这也没有被调用。

这是我制作的代码。 如果我错了,请告诉我。

谢谢你。

XAML

<UserControl x:Class="Views.Common.SubMenuPanel"
             xmlns:controls="...."                
             ....
             mc:Ignorable="d">

<UserControl.Resources>            
    <controls:SubMenuButton x:Key="TerminateSystem" 
                            ButtonName="Terminate System" 
      [[DOESN'T WORK]] -->  Execute="{Binding RelativeSource={RelativeSource  AncestorType={x:Type UserControl}}, Path=TerminateSystemCommand
                                    , Converter={StaticResource DebugDummyConverter}}"
                            ImageURI="...png"/>       

    <CollectionViewSource x:Key="LoginViewSubMenuItems">
        <CollectionViewSource.Source>
            <system:ArrayList>
                <StaticResource ResourceKey="TerminateSystem"/>
            </system:ArrayList>
        </CollectionViewSource.Source>
    </CollectionViewSource>
</UserControl.Resources>

<Grid>
   <ListBox ItemsSource="{Binding Source={StaticResource LoginViewSubMenuItems}}"/>
</Grid>

背后的代码

public partial class SubMenuPanel : UserControl
{
     public ICommand TerminateSystemCommand => new RelayCommand(() => Do Something);

     public SubMenuPanel()
     {
        InitializeComponent();

        this.DataContext = this;
     }
}

您正在将ICommand绑定到Execute属性。 您应该绑定的属性是Command ,即

<controls:SubMenuButton x:Key="TerminateSystem" 
                        ButtonName="Terminate System" 
                        Command="{Binding RelativeSource={RelativeSource  AncestorType= 
                                 {x:Type UserControl}}, Path=TerminateSystemCommand
                                    , Converter={StaticResource DebugDummyConverter}}"
                       ImageURI="...png"/> 

假设按钮中的其他属性没有引起其他问题,应该可以解决它。

编辑:

我包括了我已经验证可以工作的代码。 因为我没有你对SubMenuButton的定义, SubMenuButton我只是用了一个Button来代替:

XAML:

<UserControl.Resources>
    <Button x:Key="TerminateSystem" 
            Command="{Binding RelativeSource={RelativeSource  AncestorType={x:Type UserControl}}, Path=TerminateSystemCommand}">
        Say Hello World!!!!
    </Button>
    <CollectionViewSource x:Key="LoginViewSubMenuItems">
        <CollectionViewSource.Source>
            <system:ArrayList>
                <StaticResource ResourceKey="TerminateSystem"/>
            </system:ArrayList>
        </CollectionViewSource.Source>
    </CollectionViewSource>            
</UserControl.Resources>

<Grid>
    <ListBox ItemsSource="{Binding Source={StaticResource LoginViewSubMenuItems}}"/>
</Grid>

后面的代码:

public ICommand TerminateSystemCommand =>
        new RelayCommand(() => Console.WriteLine("Hello World!!!"));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM