Search code examples
c#wpfxamllistboxattached-properties

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


Solution

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