在我的WPF应用程序中,我有一个ComboBox,我希望能够通过编程下拉下的项目选择。我遇到的问题是,绑定 comboboxIteMiseNabled 在设置器内部无法正常工作。如果删除绑定并使用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 属性,用于其他没有问题的按钮。我在上面的问题中可以看到的唯一区别是我将属性设置在设置器中。
非常感谢您可以解决如何解决此问题的任何智慧。
在大量拖延并将头砸在键盘上后,我设法解决了解决方案。事实证明,我需要设置绑定的相对源。因为我没有为解决方案定义数据台面,所以每次我在Combobox中按下therobox中的字符时,therobox yeporceRce都会更新。这意味着找不到ComboboxeMeNables的绑定,这给我带来了上面的错误。以下是我的更新代码,我在绑定的前面添加了 datacontext ,并添加了 siveriantionsource = {reachivesource ancestortype = combobox} 。
以下是我的最终代码。
<ComboBox.ItemContainerStyle>
<Style TargetType="ComboBoxItem">
<Setter Property="IsEnabled" Value="{Binding DataContext.ComboBoxItemIsEnabled, RelativeSource={RelativeSource AncestorType=ComboBox}}" />
</Style>
</ComboBox.ItemContainerStyle>