Specify datacontext type on listbox ItemContainer in style

后端 未结 4 1721
野性不改
野性不改 2020-12-17 15:47

In a ListBox I have a ItemContainer\'s IsSelected property bound to my ViewModel\'s IsSelected property using

相关标签:
4条回答
  • 2020-12-17 16:16

    use d:DataContext like this:

    <Setter Property="d:DataContext" Value="{d:DesignInstance yourxmlns:yourItemViewModelClass}"/>
    

    You also need the following xmlnses added to the root element:

         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         mc:Ignorable="d"
    
    0 讨论(0)
  • 2020-12-17 16:18

    Addition to previous answers: to get rid of error

    Property 'DataContext' is not attachable to elements of type 'Style'

    add some dummy namespace

    xmlns:ignore="designTimeAttribute"
    

    and use it now instead of d:DataContext

    <Style TargetType="{x:Type ListBoxItem}" ignore:DataContext="{d:DesignInstance local:FooViewModel }">
    ...
    </Style>
    
    0 讨论(0)
  • 2020-12-17 16:20

    Specifying d:DataContext="{d:DesignInstance nmspc:Clz}" with other attributes of Style tag didn't help me: R# / IntelliSense really stopped highlighting properties I was binding to but the designer also showed me an error message instead of the view.

    The trick I found out is to specify <d:Style.DataContext> inside the Style tag. And it appeared to be so universal that it answers another question, about using interfaces as d:DataContext.

    Here is my answer to that question with a small example: https://stackoverflow.com/a/46637478/5598194

    0 讨论(0)
  • 2020-12-17 16:24

    As pointed out by @HighCore the solution is to specify d:DataContext attribute from blend SDK, however, it worked only when set on a Style element itsself, not in the property setter:

    <ListBox.ItemContainerStyle>
            <Style TargetType="{x:Type ListBoxItem}" d:DataContext="{d:DesignInstance local:FooViewModel }">
                <Setter Property="IsSelected" Value="{Binding IsSelected}" />
            </Style>
    </ListBox.ItemContainerStyle>
    

    This removes Resharper's warning and also changes binding Path when property is renaimed on the ViewModel. Cool!

    0 讨论(0)
提交回复
热议问题