WPF 数据绑定到窗口

本文关键字:窗口 数据绑定 WPF | 更新日期: 2023-09-27 17:56:20

我想将列表框项的数据绑定与新窗口链接

"名称"按钮应打开一个新窗口,其中包含列表框项的数据绑定。

绑定是一个.xml文件:

<People>
   <Person image="Test.jpg" company="" position="" website="" chat="" notes="">
      <Name first_name="Max" second_name="" last_name="Mustermann" salutation="" />
      <Email email1="" email2="" email3="" />
      <Phone_Numbers business="" private="" mobile="" />
      <Business_Adress street="" place="" state="" postalcode="" country="" />
      <Private_Adress street="" place="" state="" postalcode="" country="" />
   </Person>
</People>

新窗口应链接到人员的名称元素。

虽然会有多个人,但窗口应该链接到正确的人。

这是 XmlDataProvider:

<XmlDataProvider x:Name="XmlData" Source="People.xml" XPath="/People/Person" />

列表框的绑定如下所示:

<ListBox 
   Grid.Row="0" 
   IsSynchronizedWithCurrentItem="True" 
   ItemsSource="{Binding UpdateSourceTrigger=Explicit}" 
   x:Name="PeopleListBox" 
   SelectionMode="Single">
   <ListBox.ItemContainerStyle>
      <Style TargetType="ListBoxItem">
         <Setter Property="HorizontalContentAlignment" Value="Stretch" />
      </Style>
   </ListBox.ItemContainerStyle>
   <ListBox.ItemTemplate>
      <DataTemplate>
         <TextBlock>
            <TextBlock.Text>
               <MultiBinding StringFormat="{}{0}, {1} {2}">
                  <Binding XPath="Name/@last_name" />
                  <Binding XPath="Name/@first_name" />
                  <Binding XPath="Name/@second_name" />
               </MultiBinding>
            </TextBlock.Text>
         </TextBlock>
      </DataTemplate>
   </ListBox.ItemTemplate>
</ListBox>

WPF 数据绑定到窗口

除非DataContext设置为XmlData否则ItemsSource绑定将不起作用。您没有提到在哪里定义XmlDataProvider因为如果在Resources中,则需要指定x:Key而不是x:Name,然后您必须将其指定为Binding.Source。您也没有说明People.xml是什么,因为它必须作为资源添加到您的解决方案中

<Window ...>
    <Window.Resources>
        <XmlDataProvider x:Key="XmlData" XPath="/People/Person" Source="People.xml"/>
    </Window.Resources>
    <ListBox ItemsSource="{Binding Source={StaticResource XmlData}}">
        <ListBox.ItemContainerStyle>
            <Style TargetType="ListBoxItem">
                <Setter Property="HorizontalContentAlignment" Value="Stretch" />
            </Style>
        </ListBox.ItemContainerStyle>
        <ListBox.ItemTemplate>
            <DataTemplate>
                <TextBlock>
                    <TextBlock.Text>
                        <MultiBinding StringFormat="{}{0}, {1} {2}">
                            <Binding XPath="Name/@last_name" />
                            <Binding XPath="Name/@first_name" />
                            <Binding XPath="Name/@second_name" />
                        </MultiBinding>
                    </TextBlock.Text>
                </TextBlock>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Window>

或者您可以通过在代码中手动设置XmlDataProvider.Source来手动加载它