开发者

wpf - ListBox - bind SelectedItem to an xml attribute?

I have a listbox on a usercontrol which is populated by a xml file.

<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>

I would like to bind the Listbox's Selected Item to t开发者_开发百科he Machine which has a isDefault=true attribute.

My current xmldataprovider and ItemTemplate are listed below along with my ListBox markup. I was not sure if I needed to do some xpath binding in the datatemplate, or if I should make an explicit style with a trigger for this task? Or if either of those approaches would even work? One of the things I can't understand is how I can bind to an attribute that only exists on one node of my file.

<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"/>


Two possible ways you could handle this are as follows:

1) You could set the ItemContainerStyle and bind the ListBoxItem's IsSelected property to the @isDefault attribute.

<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>

Or 2) add a trigger for the 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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜