Setting properties of auto-generated listboxitem

戏子无情 提交于 2019-12-23 21:20:26

问题


I am trying to set the inputbindings of the auto-generated ListBoxItems of a databound ListBox. The code below does not work. The compiler complains that "The Property Setter 'InputBindings' cannot be set because it does not have an accessible set accessor." What is the correct syntax to set the InputBindings?

    <ListBox.ItemContainerStyle>
        <Style TargetType="{x:Type ListBoxItem}">
            <Setter Property="ListBoxItem.InputBindings">
                <Setter.Value>
                    <MouseBinding Command="{Binding OpenCommand}" Gesture="LeftDoubleClick"/>
                </Setter.Value>
            </Setter>
        </Style>
    </ListBox.ItemContainerStyle>

PS: Posting does not work with Opera 10.51


回答1:


This one is indeed tricky.

I found two proposed solutions for you, neither are very easy to implement I am afraid. I hope it works for you!

  • link one
  • Link two



回答2:


If you looking for a less "Hacky" way of doing this you can simply handle the Loaded event of the ListBoxItem like so.

        <ListBox.ItemContainerStyle>
            <Style TargetType="{x:Type ListBoxItem}">
                <EventSetter Event="Loaded" Handler="ListBoxItem_Loaded" />
            </Style>
        </ListBox.ItemContainerStyle>

Then in the event handler add your InputBindings like so.

Private Sub ListBoxItem_Loaded(ByVal sender As System.Object, ByVal e As RoutedEventArgs)
    Dim item = DirectCast(sender, ListBoxItem)
    item.InputBindings.Add(New KeyBinding(UserCommands.EditCommand, Key.Enter, ModifierKeys.None))
    item.InputBindings.Add(New KeyBinding(UserCommands.DeleteCommand, Key.Delete, ModifierKeys.None))
    item.InputBindings.Add(New MouseBinding(UserCommands.EditCommand, New MouseGesture(MouseAction.LeftDoubleClick)))
End Sub

I know it's not the ideal MVVM solution but it's the best way I have discovered.



来源:https://stackoverflow.com/questions/2572239/setting-properties-of-auto-generated-listboxitem

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!