[英]Access a class instance inside a other class from xaml in wpf
我的课看起来像这样:
public class testclass
{
public List<otherClass> references { get { return _references; } }
}
我的otherClass看起来像这样
public class otherClass
{
public string name { get; set; }
}
现在,我尝试在DataTemplate中访问此“ otherClass”
<DataTemplate x:Key="templateCore" DataType="{x:Type vm:AdminInterfaceViewModel}" >
<GroupBox DataContext="{Binding references }">
...
</DataTemplate>
这很好,或者至少我认为,beaucse intellisense能自动完成它。 但是现在我如何访问“ otherClass”的name属性?
您只需要将List绑定到ItemsControl类型,例如ListBox,DataGrid等,ItemsControl将使用List中的“ otherClass”实例作为其中每个项目的DataContext。因此,您可以找到“映射”那里:
'List<otherClass>'--'ItemsControl' 'otherClass'--'Item'
。
我想'AdminInterfaceViewModel'是您的DataContext,而'references'是它的一个属性,因此请尝试以下操作:
<DataTemplate x:Key="templateCore" DataType="{x:Type vm:AdminInterfaceViewModel}" >
<GroupBox>
<ListBox ItemsSource="{Binding references}">
<ListBox.ItemTemplate>
<DataTemplate>
<TexBox Text="{Binding name}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</GroupBox>
</DataTemplate>
>更新:
1.假设您有一个MainViewModel,其中包含名为“ AdminInterfaceViewModel”类型的名为MyViewModel的属性。
class MainViewModel
{
public AdminInterfaceViewModel MyViewModel {get; set;}
}
2.您已经将“ MainViewModel”设置为Window的DataContext,然后可以在xaml中使用属性“ MyViewModel”。
<Window>
<Grid>
<ContentControl Margin="20" Content="{Binding MyViewModel}">
</ContentControl>
</Grid>
</Window>
3.在您的ResourceDictionary中定义DataTemplate,例如'generic.xaml'。删除x:Key,然后DataTemplate将自动应用于每个'AdminInterfaceViewModel'类型实例。
<DataTemplate x:Key="templateCore" DataType="{x:Type vm:AdminInterfaceViewModel}" >
<GroupBox>
<ListBox ItemsSource="{Binding references}">
<ListBox.ItemTemplate>
<DataTemplate>
<TexBox Text="{Binding name}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</GroupBox>
</DataTemplate>
检查此链接,它可以解决您的潜在问题: MVVM模式
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.