自动生成的列表项属性设置

3

我试图设置数据绑定ListBox的自动生成的ListBoxItems的InputBindings。 下面的代码不起作用。编译器抱怨说“属性Setter 'InputBindings'不能被设置,因为它没有可访问的set访问器。” 设置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:使用Opera 10.51无法发布内容。


类似于这个问题:http://stackoverflow.com/questions/2590924/can-i-enable-previewclick-using-inputbindings-in-wpf - Joseph Sturtevant
2个回答

3
这个确实有点棘手。我为您找到了两种解决方案,但恐怕都不太容易实现。希望对您有用!

1
如果你想要一种不那么“Hacky”的方法来完成这个任务,你可以简单地处理ListBoxItem的Loaded事件,就像这样。
        <ListBox.ItemContainerStyle>
            <Style TargetType="{x:Type ListBoxItem}">
                <EventSetter Event="Loaded" Handler="ListBoxItem_Loaded" />
            </Style>
        </ListBox.ItemContainerStyle>

然后在事件处理程序中添加您的InputBindings,就像这样。

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

我知道这不是理想的MVVM解决方案,但这是我发现的最好的方法。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接