从wpf中的xaml访问另一个类中的类实例

本文关键字:实例 另一个 访问 wpf 中的 xaml | 更新日期: 2023-09-27 18:15:57

我的类是这样的:

public class testclass
{
    public List<otherClass> references { get { return _references; } }
}

我的otherClass看起来像这样

public class otherClass
{
    public string name { get; set; }
}

现在我尝试访问这个"otherClass"在一个DataTemplate

<DataTemplate x:Key="templateCore" DataType="{x:Type vm:AdminInterfaceViewModel}" >
    <GroupBox DataContext="{Binding references }">
        ...
</DataTemplate>

这个工作得很好,或者我认为至少,因为智能感知自动完成它。但是现在我怎么能得到访问的名称属性的"otherClass"?

从wpf中的xaml访问另一个类中的类实例

你所需要的就是将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,它包含一个名为MyViewModel的属性,类型为'AdminInterfaceViewModel '。

class MainViewModel
{
   public AdminInterfaceViewModel MyViewModel  {get; set;}
}

2。你已经设置了'MainViewModel'作为你的窗口的数据文本,然后你可以使用属性'MyViewModel'在xaml.

 <Window>
   <Grid>
      <ContentControl Margin="20" Content="{Binding MyViewModel}">
      </ContentControl>
    </Grid>
 </Window>

3。在ResourceDictionary中定义DataTemplate,例如'generic.xaml'。删除x:键,然后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模式