2010-09-20 81 views
0

我有一個由xml文件填充的usercontrol上的列表框。wpf - 列表框 - 將SelectedItem綁定到xml屬性?

<Machines xmlns=""> 
    <Machine Name="Prod1" IP="192.168.1.200" isDefault="true" InstanceName="sql08" /> 
    <Machine Name="Prod2" IP="192.168.1.101" /> 
    <Machine Name="Test1" IP="192.168.1.103" /> 
    <Machine Name="Test2" IP="192.168.1.104" /> 
</Machines> 

我想將Listbox的Selected Item綁定到具有isDefault = true屬性的機器上。

我的當前xmldataprovider和ItemTemplate與我的列表框標記一起列出。我不確定是否需要在數據模板中執行一些xpath綁定,或者是否應該爲此任務創建一個帶有觸發器的顯式樣式?或者,如果這些方法中的任何一種都可以工我無法理解的一件事是我如何綁定到僅存在於我的文件的一個節點上的屬性。你可以處理這個

<XmlDataProvider x:Key="DataList" Source="XML\ListboxSettings.xml" XPath="Machines/Machine"/> 
     <DataTemplate x:Key="MachineDataTemplate"> 
      <TextBlock Text="{Binding [email protected]}" ToolTip="{Binding [email protected]}" /> 
     </DataTemplate> 

<ListBox Name="MerlinsListbox" Margin="5" Height="{Binding Height, ElementName=border}" Background="#FF252525" FontFamily="Consolas" FontSize="16" Foreground="#FFFBF9F9" 
        ItemsSource="{Binding}" 
        ItemTemplate="{StaticResource MerlinDataTemplate}" 
        IsSynchronizedWithCurrentItem="true"/> 

回答

0

兩種可能的方法如下:

1)你可以設置ItemContainerStyle和一個ListBoxItem的IsSelected屬性綁定到@isDefault屬性。

<ListBox Name="MerlinsListbox" Margin="5" 
      Background="#FF252525" FontFamily="Consolas" FontSize="16" Foreground="#FFFBF9F9" 
      ItemsSource="{Binding Source={StaticResource DataList}}" 
      ItemTemplate="{StaticResource MachineDataTemplate}" 
      IsSynchronizedWithCurrentItem="true"> 
    <ListBox.ItemContainerStyle> 
     <Style TargetType="ListBoxItem"> 
      <Setter Property="IsSelected" Value="{Binding [email protected], Mode=OneTime}"/> 
     </Style> 
    </ListBox.ItemContainerStyle> 
</ListBox> 

或2)添加一個觸發器的ItemContainerStyle:

<ListBox ...> 
    <ListBox.ItemContainerStyle> 
     <Style TargetType="ListBoxItem"> 
      <Style.Triggers> 
       <DataTrigger Binding="{Binding [email protected]}" Value="true"> 
        <Setter Property="IsSelected" Value="True"/> 
       </DataTrigger> 
      </Style.Triggers> 
     </Style> 
    </ListBox.ItemContainerStyle> 
</ListBox> 
+0

謝謝Karmicpuppet。這對我來說非常合適。 – TWood 2010-09-20 19:01:34

+0

不客氣。 ;) – ASanch 2010-09-20 19:07:13

相關問題