我有像下面的标记
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>
视图模型
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
}
}
}
位于我的viewmodel上的布尔属性 IsItemEnabled 对于此setter无法访问,并且绑定不起作用。据我所知,粘合剂试图找到不在MyViewModel中的属性。怎么解决?我可以只为组合框设置datacontext,或者在这种情况下还有其他方法吗?
答案 0 :(得分:1)
尝试
<Setter Property="IsEnabled" Value="{Binding Path=DataContext.IsItemEnabled,RelativeSource={RelativeSource AncestorType=ComboBox}}" />
答案 1 :(得分:0)
此代码在新的测试应用程序中正常工作正常,但是当我在主项目上复制此组合框时,我已经遇到上述异常。
<ComboBox Grid.Column="0" Width="150" Height="32" IsSynchronizedWithCurrentItem="True"
ItemsSource="{Binding OptimizationTypes}" DisplayMemberPath="TypeName"
SelectedIndex="{Binding SomeSelectedItem, UpdateSourceTrigger=PropertyChanged}"
Margin="12,11,-162,-43">
<ComboBox.DataContext>
<local:MyViewModel />
</ComboBox.DataContext>
<ComboBox.ItemContainerStyle>
<Style TargetType="{x:Type ComboBoxItem}">
<Setter Property="IsEnabled" Value="{Binding Path=IsItemEnabled}" />
</Style>
</ComboBox.ItemContainerStyle>
</ComboBox>
一个区别是视图模型在测试应用程序中有默认构造函数。不幸的是,我无法在主项目的视图模型中添加第二个构造函数,因此我也无法将我的视图模型用作数据上下文。有没有解决方法?