簡體   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