C# 在WPF MVVM中的Setter属性内绑定ComboBoxItem值
在我的wpf应用程序中,我有一个组合框,我希望它能够以编程方式禁用下拉列表中的项目选择。我遇到的问题是绑定ComboBoxItemIsEnabled在setter中没有按预期工作。如果删除绑定并使用True或False,它将按预期工作 XAMLC# 在WPF MVVM中的Setter属性内绑定ComboBoxItem值,c#,wpf,xaml,mvvm,C#,Wpf,Xaml,Mvvm,在我的wpf应用程序中,我有一个组合框,我希望它能够以编程方式禁用下拉列表中的项目选择。我遇到的问题是绑定ComboBoxItemIsEnabled在setter中没有按预期工作。如果删除绑定并使用True或False,它将按预期工作 XAML <ComboBox ItemsSource="{Binding Path=ConfigItems.Result}" DisplayMemberPath="Name" IsEditable="True" FontS
<ComboBox
ItemsSource="{Binding Path=ConfigItems.Result}"
DisplayMemberPath="Name"
IsEditable="True"
FontSize="14"
SelectedItem="{Binding SelectedItem, Mode=TwoWay}"
IsTextSearchEnabled="False"
Text="{Binding Path=ConfigItem,
UpdateSourceTrigger=LostFocus,
TargetNullValue={x:Static sys:String.Empty}}"
b:ComboBoxBehaviors.OnButtonPress="True">
<ComboBox.ItemContainerStyle>
<Style TargetType="ComboBoxItem">
<Setter Property="IsEnabled" Value="{Binding ComboBoxItemIsEnabled}" />
</Style>
</ComboBox.ItemContainerStyle>
</ComboBox>
我正在使用相同的mvvm方法将按钮的IsEnabled属性定位到其他没有问题的地方。我在上面的问题中看到的唯一区别是,我在setter中设置了属性
非常感谢您在如何解决这个问题上提供的所有智慧 我拖延了很久,头撞在键盘上,终于找到了解决办法。事实证明,我需要为绑定设置相对源。因为我没有为我的解决方案定义DataContext,所以每次我在组合框中按下一个字符时,ItemSource都会更新。这意味着找不到ComboBoxItemIsEnabled绑定,导致出现上述错误。下面是我的更新代码,我在绑定前添加了DataContext,并在绑定后添加了RelativeSource={RelativeSource AncestorType=ComboBox} 下面是我的最终代码
<ComboBox.ItemContainerStyle>
<Style TargetType="ComboBoxItem">
<Setter Property="IsEnabled" Value="{Binding DataContext.ComboBoxItemIsEnabled, RelativeSource={RelativeSource AncestorType=ComboBox}}" />
</Style>
</ComboBox.ItemContainerStyle>
尝试使用bool而不是string@sTrenat谢谢你的回复,我一定会试一试的。我原以为这可能是原因,但驳回了它,因为另一个控制不要求我这么做。如果其他人想否决我的问题,请留下评论,说明原因。这样做似乎毫无意义,我也不知道我的问题出了什么问题。
System.Windows.Data Error: 40 : BindingExpression path error: 'ComboBoxItemIsEnabled' property not found on 'object' ''ConfigItem' (HashCode=56037929)'. BindingExpression:Path=ComboBoxItemIsEnabled; DataItem='ConfigItem' (HashCode=56037929); target element is 'ComboBoxItem' (Name=''); target property is 'IsEnabled' (type 'Boolean')
<ComboBox.ItemContainerStyle>
<Style TargetType="ComboBoxItem">
<Setter Property="IsEnabled" Value="{Binding DataContext.ComboBoxItemIsEnabled, RelativeSource={RelativeSource AncestorType=ComboBox}}" />
</Style>
</ComboBox.ItemContainerStyle>