如何将 DataTemplate 数据类型绑定到接口? [英] How to bind DataTemplate datatype to interface?

查看:27
本文介绍了如何将 DataTemplate 数据类型绑定到接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个复合松散耦合的 MVVM WPF 应用程序,父 VM 中的子 VM 是接口而不是类实例,例如

I am writing a composite loosely coupled MVVM WPF application and child VMs in a parent VM are interfaces rather than class instances, e.g.

public IChildViewModel { get; set; }

现在如何使用 DataTemplate 呈现此属性?喜欢:

Now how do I render this property using a DataTemplate? like:

<DataTemplate DataType="{x:Type contracts:IChildViewModel}">

我理解由于接口的性质(多重继承等),WPF 不允许这种直接绑定.但是由于接口应该广泛用于松散耦合的应用程序中,是否有任何解决方法可以将 DataTemplate 绑定到接口?谢谢.

I understand due to the nature of interfaces (multiple inheritance etc.) WPF does not allow this direct binding. But as interfaces should be used widely in loosely coupled applications, is there any workaround to bind DataTemplate to interfaces? Thanks.

推荐答案

您可以通过明确告诉 wpf 您正在绑定到接口字段来绑定到接口:

You can bind to interfaces by telling wpf explicitly that you are binding to an interface field:

(请注意 ViewModelBase 只是一个实现 INotifyPropertyChanged 接口的基类)

(Please note that ViewModelBase is simply a base-class that implements the INotifyPropertyChanged interface)

public class Implementation : ViewModelBase, IInterface
{
    private string textField;

    public string TextField
    {
        get
        {
            return textField;
        }
        set
        {
            if (value == textField) return;
            textField = value;
            OnPropertyChanged();
        }
    }
}

public interface IInterface
{
    string TextField { get; set; }
}

然后在 ViewModel 上:

Then on the ViewModel:

private IInterface interfaceContent;
public IInterface InterfaceContent
{
    get { return interfaceContent; }
}

最后是使之成为可能的 Xaml:

And finally the Xaml that makes it possible:

<ContentControl Grid.Row="1" Grid.Column="0" Content="{Binding InterfaceContent}">
    <ContentControl.ContentTemplate>
        <DataTemplate DataType="{x:Type viewModels:IInterface}">
            <TextBox Text="{Binding Path=(viewModels:IInterface.TextField)}"/>
        </DataTemplate>
    </ContentControl.ContentTemplate>
</ContentControl>

如您所见,绑定明确引用了IInterface"定义.

As you can see, the binding refers explicitly to the 'IInterface' definiton.

这篇关于如何将 DataTemplate 数据类型绑定到接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆