如何解决RelativeSource从未调用
我想将后面代码中的命令绑定到ICommand
中的用户控制按钮(UserControl.Resources
)
所以我用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
的定义,因此我只使用了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!!!"));
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。