【发布时间】:2019-09-10 09:19:52
【问题描述】:
我有一个绑定到父类列表的项目控件。 我需要在数据模板中绑定子类的属性。
这些是我的课程
public class Parent {
private string _name;
public string Name
{
get { return _name; }
set
{
if (Equals(value, _name)) return;
_name = value;
OnPropertyChanged(nameof(Name));
}
}
}
public class Child1 : Parent{
private string _prob1;
public string Prob1
{
get { return _prob1; }
set
{
if (Equals(value, _prob1)) return;
_prob1= value;
OnPropertyChanged(nameof(Prob1));
}
}
}
public class Child2 : Parent{
private string _prob2;
public string Prob2
{
get { return _prob2; }
set
{
if (Equals(value, _prob2)) return;
_prob2= value;
OnPropertyChanged(nameof(Prob2));
}
}
}
在我的视图模型中,我有一个可观察的父类集合
public ObservableCollection<Parent> ParentList { get; set; }
还有我的 xaml 代码
<ItemsControl ItemsSource="{Binding ParentList }">
<ItemsControl.ItemTemplate>
<DataTemplate
DataType="domainObject:Child1">
<TextBlock Text="{Binding Name}" Margin="5" IsEnabled="False" HorizontalAlignment="Center" Height="22" Background="Transparent" />
<TextBlock Text="{Binding Prob1}" Margin="5"HorizontalAlignment="Center" Height="22" />
我想将 2. 文本框绑定到子类的属性。
有什么简单的方法可以解决这个问题吗?
【问题讨论】:
-
从您在此处显示的内容来看,您的 Parent、Child1 和 Child2 类之间没有任何关系。那你到底在问什么?如果 Child1 将 派生 来自 Parent,则您的 XAML 将按原样工作。请注意,设置明确用作 ItemsControl 的 ItemTemplate 的 DataTemplate 的 DataType 属性是没有意义的。
-
对不起,我忘了加“:父母”。文本块不包含任何值,我认为绑定有问题?
-
请看答案。请注意,父/子关系通常由组合而非继承建模。换句话说,基类(或超类)通常不称为父类。
标签: c# wpf parent-child datatemplate itemscontrol