Cha*_*lie 27 wpf types bind interface datatemplate
我正在编写一个复合松散耦合的MVVM WPF应用程序,父虚拟机中的子虚拟机是接口而不是类实例,例如
public IChildViewModel { get; set; }
Run Code Online (Sandbox Code Playgroud)
现在如何使用DataTemplate呈现此属性?喜欢:
<DataTemplate DataType="{x:Type contracts:IChildViewModel}">
Run Code Online (Sandbox Code Playgroud)
我理解由于接口的性质(多重继承等),WPF不允许这种直接绑定.但是由于接口应该在松散耦合的应用程序中广泛使用,是否有任何解决方法将DataTemplate绑定到接口?谢谢.
您可以通过明确告诉wpf绑定到接口字段来绑定到接口:
(请注意,ViewModelBase只是一个实现INotifyPropertyChanged接口的基类)
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; }
}
Run Code Online (Sandbox Code Playgroud)
然后在ViewModel上:
private IInterface interfaceContent;
public IInterface InterfaceContent
{
get { return interfaceContent; }
}
Run Code Online (Sandbox Code Playgroud)
最后,Xaml使它成为可能:
<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>
Run Code Online (Sandbox Code Playgroud)
如您所见,绑定明确指的是"IInterface"定义.
| 归档时间: |
|
| 查看次数: |
9195 次 |
| 最近记录: |