订阅DataTemplate中控件的事件的最佳实践

本文关键字:最佳 事件 订阅 控件 DataTemplate | 更新日期: 2023-09-27 17:59:23

我有一个用于自定义控件的ControlTemplate,它看起来像这样(简化):

<ControlTemplate TargetType="CustomControl">
    <Grid>
        <Grid.Resources>
            <DataTemplate TargetType="CustomClassA">
                <TextBlock Text={Binding ClassASpecificProperty}" />
            </DataTemplate>
            <DataTemplate TargetType="CustomClassB">
                <TextBlock Text={Binding ClassBSpecificProperty}" />
            </DataTemplate>
        </Grid.Resources>
        <ContentControl Content="{TemplateBinding Content}" />
    </Grid>
</ControlTemplate>

其美妙之处在于,特定的Content取决于其类型(A或B),由为每种类型定义的DataTemplate s引起,显示方式不同。

然而。有时不仅仅有TextBlocks。想象一下这些数据模板中有按钮。有时您希望使用某些方法订阅Click事件。但这些控制模板通常在ResourceDictionary中,因此后面没有代码用于为相应的Click处理程序放置方法。

我看到了三种不同的解决方案:

  • 创建一个CustomResourceDictionary,并附加代码隐藏文件
  • 重写OnApplyTemplate方法(不过我并不真正理解这一点)并以编程方式订阅事件
  • 处理附加的消息并在"ViewModel"中处理UI逻辑

实现这一目标的最佳实践是什么?或者有"更好"的解决方案吗?那么性能呢?

订阅DataTemplate中控件的事件的最佳实践

您可以使用DelegateCommand将按钮等绑定到ViewModel中的命令。

<Button Command="{Binding MyCommand}"/>

ViewModel:

public DelegateCommand MyCommand {get;set;} //INotifyPropertyChanged, etc.
private void ExecuteMyCommand()
{
    //Do stuff here.
}
public MyViewModel()
{
    MyCommand = new DelegateCommand(ExecuteMyCommand);
}