简体   繁体   English

在ComboBoxItem上绑定IsEnabled不起作用

[英]Binding IsEnabled on ComboBoxItem does not work

I have this model: 我有这个型号:

public class Option : BindableBase
{
    private bool _enabled;
    public bool Enabled
    {
        get
        {
            return _enabled;
        }
        set
        {
            SetProperty(ref _enabled, value);
        }
    }

    private string _value;
    public string Value
    {
        get
        {
            return _value;
        }
        set
        {
            SetProperty(ref _value, value);
        }
    }
}

In my viewmodel, I got a list Options of type ObservableCollection<Option> . 在我的视图模型,我得到了一个列表Options类型ObservableCollection<Option>

I use this XAML piece of code: 我使用这段XAML代码:

<ComboBox Width="200"
          ItemsSource="{Binding Options}">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding Value}"/>
                <TextBlock Text="{Binding Enabled}"/>
            </StackPanel>
        </DataTemplate>
     </ComboBox.ItemTemplate>
     <ComboBox.ItemContainerStyle>
         <Style TargetType="ComboBoxItem">
             <Setter Property="IsEnabled" Value="{Binding Enabled}"/>
         </Style>
     </ComboBox.ItemContainerStyle>
 </ComboBox>

I add some Option in my list, some of them have the Enabled property set to true while others do not. 我在列表中添加了一些Option ,其中一些OptionEnabled属性设置为true而其他选项则没有。

However, the ones having the property to false are still enabled in the ComboBox and I can select them (while I should not!). 但是,具有false属性的那些仍然在ComboBox启用,我可以选择它们(我不应该!)。 When using this line of code: 使用这行代码时:

 <Setter Property="IsEnabled" Value="false"/>

The options are effectively disabled (I can't select any of them) but I'd like to use some binding. 选项被有效禁用(我不能选择其中任何一个),但我想使用一些绑定。 Can someone explain what I'm doing wrong here? 谁能解释我在这里做错了什么?

You are setting IsEnabled on the content of your ComboBoxItem while you would need to set it on the ComboBoxItem itself. 您在ComboBoxItem的内容上设置IsEnabled,而您需要在ComboBoxItem本身上设置它。 You would need to set the binding in the ItemContainerStyle. 您需要在ItemContainerStyle中设置绑定。 I'm not sure if bindings are supported in style setters though. 我不确定样式设置器是否支持绑定。 If they are not, then you might need to use a workaround to set up the binding. 如果不是,则可能需要使用变通方法来设置绑定。

Maybe you need to use path instead. 也许你需要使用路径。 You can try this : 你可以试试这个:

<Setter Property="IsEnabled" Value="{Binding Path=Enabled}"/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM