Disable separator selection in data bound combo box in WPF

风流意气都作罢 提交于 2019-12-06 07:41:59

Instead of setting "Focusable" as suggested by Meleak, set "IsEnabled" to false instead in the Setter.

<DataTrigger Binding="{Binding Code}" Value="-"> 
    <Setter Property="IsEnabled" Value="False"/>
    <Setter Property="Template"> 
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type ComboBoxItem}"> 
                <Separator HorizontalAlignment="Stretch"/> 
            </ControlTemplate> 
        </Setter.Value> 
    </Setter> 
</DataTrigger> 

I tried the suggestion mentioned above and I was still not able to get the separator. Instead it added a blank selectable entry in the combo box. Finally this is what worked for me.

I set the bound data item as NULL. And my XAML looks so:

<DataTrigger Binding="{Binding}" Value="{x:Null}">
    <Setter Property="IsEnabled" Value="False"/>
    <Setter Property="Template"> 
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type ComboBoxItem}"> 
                <Separator HorizontalAlignment="Stretch"/> 
            </ControlTemplate> 
        </Setter.Value> 
    </Setter> 
</DataTrigger>

The selectable item is not the Separator itself but the ComboBoxItem containing a Separator.
Try to set Focusable="False" in the DataTrigger. This should make the ComboBoxItem "unselectable"

Update
Fixed Setter position

<DataTrigger Binding="{Binding Code}" Value="-"> 
    <Setter Property="Focusable" Value="False"/>
    <Setter Property="Template"> 
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type ComboBoxItem}"> 
                <Separator HorizontalAlignment="Stretch" IsEnabled="False"/> 
            </ControlTemplate> 
        </Setter.Value> 
    </Setter> 
</DataTrigger> 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!