使单行不可聚焦

Making it so a single line is not focusable

我找到了使整个 listBox 不可聚焦的方法,但我想知道是否有办法使 lsitbox 中的单行不可聚焦?

<ListBox.ItemContainerStyle>
    <Style TargetType="Control">
    <Setter Property="Focusable" Value="False" />
    </Style>
 </ListBox.ItemContainerStyle>

简单,如果您使用的是 MVVM:

<ListBox.ItemContainerStyle>
    <Style TargetType="Control">
        <Style.Triggers>
            <DataTrigger Binding="{Binding DontFocusMeBro}" Value="True">
                <Setter Property="Focusable" Value="False" />
            </DataTrigger>
        </Style.Triggers>
    </Style>
</ListBox.ItemContainerStyle>

这将适用于任何类型的属性,而不仅仅是 bool,只要您要匹配的值可以从触发器的 Value 属性中的字符串转换而来。如果你的项目 属性 是 bool 当项目 应该 是可聚焦的时,这是正确的,你可以更容易地做到这一点:

<ListBox.ItemContainerStyle>
    <Style TargetType="Control">
        <Setter Property="Focusable" Value="{Binding MakeMeFocusable}" />
    </Style>
</ListBox.ItemContainerStyle>

这假设您的 ListBox 填充了您编写的 C# class 的实例:

public class MyListItem : MyViewModelBase 
{
    private bool _dontFocusMeBro;
    public bool DontFocusMeBro {
        get { return _dontFocusMeBro; }
        set {
            if (value != _dontFocusMeBro) {
                _dontFocusMeBro = value;
                OnPropertyChanged();
            }
        }
    }

    private bool _makeMeFocusable;
    public bool MakeMeFocusable
    {
        get { return _makeMeFocusable; }
        set
        {
            if (value != _makeMeFocusable)
            {
                _makeMeFocusable = value;
                OnPropertyChanged();
            }
        }
    }

    //  ... other properties ...
}

如果你用字符串或其他东西填充它,或者更糟的是在代码隐藏的循环中添加 ListBoxItem 实例,你将不得不编写转换器或其他东西。如果你给我更多细节,我可以让你了解如何使用你自己的代码来实现它。