WPF数据绑定到窗口

时间:2014-04-03 13:45:44

标签: c# wpf data-binding listbox

我想将列表框项的DataBinding与新窗口链接

A"姓名"按钮应该使用列表框项的DataBinding打开一个新窗口。

Binding是一个.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>

1 个答案:

答案 0 :(得分:0)

除非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来手动加载