繁体   English   中英

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

[英]Best practice for subscribing to events of a control in a DataTemplate?

我有一个用于自定义控件的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引起的。

然而。 有时不只是TextBlock 想象一下在这些DataTemplates中有按钮。 有时,您想使用某些方法来订阅Click事件。 但是这些控件模板通常位于ResourceDictionary ,因此没有用于放置相应Click处理程序方法的代码

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

  • 使用文件后面的代码创建CustomResourceDictionary
  • 重写OnApplyTemplate方法(尽管我不太了解),并以编程方式订阅事件
  • 处理收到的消息并处理“ ViewModel”中的UI逻辑。 丑陋!

实现此目的的最佳实践是什么? 还是有“更好”的解决方案? 那性能呢?

您可以使用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);
}

暂无
暂无

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

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