简体   繁体   中英

How do I set the Selector.IsSelected attached property to ListBox items in code?

Reference to WPF 4 Unleashed page 281: "Selector also supports two attached properties that can be applied to individual items".

<ListBox Name="listBox1">
    <sys:String>Fred</sys:String>
    <sys:String Selector.IsSelected="True">Wilma</sys:String>   <- Error
    <ListBoxItem Selector.IsSelected="True">
        <sys:String>Barney</sys:String>
    </ListBoxItem>
</ListBox>

Seems I can't apply Selector.IsSelected to the second item because it isn't a DependencyObject is that right? Can't do it from code either.

Another question, if I want to add strings to the Items collection in XAML is there a way to separate them without wrapping them inside <sys:String></sys:String> ?

What can I say

1) Yes you're correct you can only attach an attached property to a DependencyObject . An alternative would be to use <ListBox SelectedIndex="1"> ...

2) You have to wrap the strings in something, but it could be:

<sys.String>Fred</sys.String>
<ListBoxItem>Fred</ListBoxItem>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM