我在usercontrol上有一个列表框,该列表框由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属性的Machine。
下面列出了我当前的xmldataprovider和ItemTemplate以及我的ListBox标记。我不确定是否需要在datatemplate中进行一些xpath绑定,或者我是否应该使用触发器为此任务创建一个显式样式?或者,如果这些方法中的任何一种甚至可行?我无法理解的一件事是我如何绑定到仅存在于我的文件的一个节点上的属性。
<XmlDataProvider x:Key="DataList" Source="XML\ListboxSettings.xml" XPath="Machines/Machine"/>
<DataTemplate x:Key="MachineDataTemplate">
<TextBlock Text="{Binding XPath=@Name}" ToolTip="{Binding XPath=@IP}" />
</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 :(得分: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 XPath=@isDefault, Mode=OneTime}"/>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
或者2)为ItemContainerStyle添加一个触发器:
<ListBox ...>
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Style.Triggers>
<DataTrigger Binding="{Binding XPath=@isDefault}" Value="true">
<Setter Property="IsSelected" Value="True"/>
</DataTrigger>
</Style.Triggers>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>