简体   繁体   English

如何将嵌套元素的属性绑定到 viewmodel 属性

[英]How to bind the property of nested element to the viewmodel property

I have markup like following我有如下标记

XAML XAML

    <ComboBox Grid.Row="0" Margin="15,54,352,231" IsSynchronizedWithCurrentItem="True"
                      ItemsSource="{Binding OptimizationTypes}" DisplayMemberPath="TypeName"
                      SelectedIndex="{Binding SelectedIndex, UpdateSourceTrigger=PropertyChanged}">
                <ComboBox.DataContext >
                    <viewModels:MyViewModel />
                </ComboBox.DataContext>
                <ComboBox.ItemContainerStyle>
                    <Style TargetType="{x:Type ComboBoxItem}">
                        <Setter Property="IsEnabled" Value="{Binding IsItemEnabled}" />
                    </Style>
                </ComboBox.ItemContainerStyle>
            </ComboBox>

ViewModel视图模型

using System.Collections.Specialized;

namespace WpfApplication
{
    public class MyViewModel : INotifyCollectionChanged
    {
        public event NotifyCollectionChangedEventHandler CollectionChanged;
        public bool IsItemEnabled { get; set; }

        public MyViewModel(IBaseControlElement baseControlElement)
        {
            //some code
        }
    }
}

The Boolean property IsItemEnabled located on the my viewmodel doesn't accesible for this setter and binding doesn't work.位于我的视图模型上的布尔属性IsItemEnabled不可访问此 setter 并且绑定不起作用。 As far as i see binder trying to find the property not in MyViewModel.据我所知,活页夹试图找到不在 MyViewModel 中的属性。 How to fix it?如何解决? Can i set datacontext only for the combobox, or there are any others approaches in this case?我可以只为组合框设置数据上下文,或者在这种情况下还有其他方法吗?

尝试

<Setter Property="IsEnabled" Value="{Binding Path=DataContext.IsItemEnabled,RelativeSource={RelativeSource AncestorType=ComboBox}}" />

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

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