Wpf 如何使自定义控件的元素在视图上可访问以将其订阅到命令?
我有一个自定义窗口,它有两个按钮。一个按钮名为“确定按钮”,另一个按钮名为“取消按钮”Wpf 如何使自定义控件的元素在视图上可访问以将其订阅到命令?,wpf,xaml,custom-controls,caliburn.micro,Wpf,Xaml,Custom Controls,Caliburn.micro,我有一个自定义窗口,它有两个按钮。一个按钮名为“确定按钮”,另一个按钮名为“取消按钮” <Style TargetType="{x:Type WindowCustom}"> "Properties Here" <Setter.Value> <ControlTemplate TargetType="{x:Type WindowCustom}"> <Border BorderBr
<Style TargetType="{x:Type WindowCustom}">
"Properties Here"
<Setter.Value>
<ControlTemplate TargetType="{x:Type WindowCustom}">
<Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}">
<Button x:Name="OKButton" Content="OK"/>
<Button x:Name="CancelButton" Content="Cancel"/>
"Closing Tags"
假设所有其他创建自定义窗口所需的代码都存在。我编写了几个路由命令,让我的OKButton做我想做的事情。这并不理想,因为我以前实现的按钮使用了ActionMessage(Caliburns的说法是Command)
如何通过XAML访问控件以将其添加到操作消息中?
我能做的就是在自定义窗口上写下我的按钮控件的名称
<lc:WindowCustom OKButton="">
我不知道从这里该怎么办 您可以向
WindowCustom
类添加依赖项属性:
public static readonly DependencyProperty OkCommandProperty =
DependencyProperty.Register("OkCommand", typeof(ICommand),
typeof(CustomWindow), new FrameworkPropertyMetadata(null));
public ICommand OkCommand
{
get { return (ICommand)GetValue(OkCommandProperty); }
set { SetValue(OkCommandProperty, value); }
}
…并将控制模板
中的按钮
的命令
属性绑定到此属性:
<Button x:Name="OKButton" Content="OK" Command="{Binding OkCommand, RelativeSource={RelativeSource TemplatedParent}}"/>
单击
按钮
时将调用该命令。当然,您也可以对取消按钮执行相同的操作。只需添加另一个依赖属性。此答案针对希望在自定义控件上使用ActionMessage功能的Caliburn用户。
我的自定义窗口上的按钮如下所示
<lc:ButtonCustom x:Name="PART_OKButton">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<cal:ActionMessage MethodName="{Binding OkCommand, RelativeSource={RelativeSource TemplatedParent}}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</lc:ButtonCustom>
我将ICommand更改为字符串数据类型,因为ActionMessage接受字符串
最后,在窗口中,我将要执行的操作分配给操作消息
<lc:WindowCustom <!--xmlns tags and other dependency proerties-->
OkCommand="SaveHistoryEntry">
OkCommand=“SaveHistoryEntry”
它起作用了 我很快就会用caliburn发布我的实现。谢谢你,伙计!
<lc:WindowCustom OkCommand="{Binding YourViewModelCommandProperty}">
<lc:ButtonCustom x:Name="PART_OKButton">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<cal:ActionMessage MethodName="{Binding OkCommand, RelativeSource={RelativeSource TemplatedParent}}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</lc:ButtonCustom>
public string OkCommand
{
get { return (string)GetValue(OkCommandProperty); }
set { SetValue(OkCommandProperty, value); }
}
public static readonly DependencyProperty OkCommandProperty = DependencyProperty.Register("OkCommand", typeof(string), typeof(WindowCustom),
new FrameworkPropertyMetadata(null));
<lc:WindowCustom <!--xmlns tags and other dependency proerties-->
OkCommand="SaveHistoryEntry">