开发者

Cannot set ComboBoxItem.IsEnabled to a Binding

I've had a day full of Silverlight idiosynchrasies, including this little doozy:

<ComboBox>
    <ComboBox.ItemContainerStyle>
        <Style TargetType="ComboBoxItem">
            <Setter Property="IsEnabled" Value="{Binding IsEnabled}"/>
        </Style>
    </ComboBox.ItemContainerStyle>

    <ComboBoxItem>First</ComboBoxItem>
    <ComboBoxItem>Second</ComboBoxItem>
</ComboBox>

The above fails with:

  System.Windows.Markup.XamlParseException occurred
    Message=Set property '' threw an exception. [Line: 88 Position: 52]
    LineNumber=88
    LinePosition=52
    StackTrace:
         at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)
    InnerException: System.NotSupportedException
         Message=Cannot set read-only property ''.
         StackTrace:
              at MS.Internal.XamlMemberInfo.SetValue(Object target, Object value)
              at MS.Internal.XamlManagedRuntimeRPInvokes.SetValue(XamlTypeToken inType, XamlQualifiedObject& i开发者_开发知识库nObj, XamlPropertyToken inProperty, XamlQualifiedObject& inValue)
         InnerException: 

If I change {Binding IsEnabled} to simply True or False, then it works fine.

I'm utterly confused because ComboBoxItem.IsEnabled is a DependencyProperty and is not readonly, so the error message is complete rubbish.

Any ideas how to fix this? Ultimately, all I want to do is have the IsEnabled property on the ComboBoxItems to be bound to a property on my view model.

PS. Yes, I also tried binding ItemsSource to my view model collection and ensuring that the IsEnabled property actually existed on my view models. Same problem.


I worked around this for now by overriding PrepareContainerForItemOverride as follows:

protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
{
    base.PrepareContainerForItemOverride(element, item);

    // can't do this in ItemContainerStyle because SL is poo
    (element as ComboBoxItem).SetBinding(ComboBoxItem.IsEnabledProperty, new Binding("IsEnabled"));
}

Is this really still not possible in SL4? Seems completely ridiculous to me, as have all the other problems I've run into today.


Perhaps this is way off base (and way late) but could it have to do with the naming of the property on the bound object matching the property you are setting?

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

Can you do it in XAML if the path isn't IsEnabled?


I know that this thread is old but today I faced the same problem and I just want to confirm that what Dave Lowther suggested is the problem of this case. After changing property name from IsEnabled to IsComboBoxItemEnabled everything started working properly, so just don't use IsEnabled name in your model

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜