在我的wpf应用程序中,我有一个ComboBox,我希望能够以编程方式禁用下拉列表中的项目选择。我遇到的问题是绑定 ComboBoxItemIsEnabled 在setter中没有按预期工作。如果删除绑定并使用True或False,它将按预期工作。
XAML
<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>
C#
private string _comboBoxItemIsEnabled = "True";
public string ComboBoxItemIsEnabled
{
get
{
return this._comboBoxItemIsEnabled;
}
set
{
this.SetProperty(ref this._comboBoxItemIsEnabled, value);
}
}
public async Task<ConfigItem[]> LoadConfigItemsAsync(string partialName)
{
try
{
if (partialName.Length >= 5)
{
this.ComboBoxItemIsEnabled = "True";
return await this._Service.GetConfigItemsAsync(partialName);
}
this.ComboBoxItemIsEnabled = "False";
return new[] { new ConfigItem("Minimum of 5 characters required", null)};
}
catch (Exception)
{
this.ComboBoxItemIsEnabled = "False";
return new[] { new ConfigItem("No results found", null) };
}
}
当设置ComboBoxIsEnabled时,我也从调试控制台收到以下错误。
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')
我使用相同的mvvm方法将 IsEnabled 属性定位到其他没有问题的按钮。我在上面的问题中看到的唯一区别是我在setter中设置了属性。
非常感谢你能解决这个问题的任何智慧。
答案 0 :(得分:1)
经过多次拖延和撞击键盘后,我设法找到了解决方案。事实证明,我需要设置绑定的相对来源。因为我没有为我的解决方案定义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>