我尝试搜索了很多线程,我发现了几个非常接近但不完全是我想要的。经过一天的搜索,我决定问问。如果我遗漏了什么,我深表歉意,我觉得这很常见,但我似乎不太明白。
我有一个绑定(bind)到 ViewModel 的 UserControl,它有一个带有 ItemsSource=ObservableCollection 的列表框,它是 ViewModel 的一个属性,如下所示:
每当我选择一个项目时,我都会根据特定条件对其他几个项目调用 SomeObject.IsEnabled = false。我想将列表框项目绑定(bind)到 IsEnabled 属性,这样我就可以在进行选择时将任何项目变灰。
View 模型:
Class ViewModel : PropertyNotificationObject
{
private ObservableCollection<SomeObject> m_list;
public ObservableCollection<SomeObject> List {get; set;} //notifying properly
private void selectedItem()
{
//several in SomeObjects in List sets IsEnabled = false
}
}
项目等级
class SomeObject : PropertyNotificationObject
{
private bool m_isEnabled;
public IsEnabled { get; set; } //notifying properly
}
XAML
<DataTemplate x:Key="ListTemplate">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding ., Converter={someConverterObjectToString}}"/>
</Grid>
</DataTemplate>
<ListBox ItemsSource="{Binding List}" ItemTemplate="{StaticResource ListTemplate}"/>
我试过在 ListBox.ItemContainerStyle 和 DataTemplate 中使用 StyleTriggers,如下所示,但我不知道如何访问 SomeOject.IsEnabled 属性。
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Style.Triggers>
<DataTrigger Binding={???????? I can't get to my SomeObject properties.}
</Style.Triggers>
</Style>
</ListBox.ItemContainerStyle>
抱歉缺少颜色,我是新来的,真的不知道如何很好地使用编辑器。
提前致谢。
最佳答案
{Binding IsEnabled}
在您的 ItemContainerStyle
中应该可以完成这项工作。查看 VS 调试窗口是否存在绑定(bind)错误
编辑或直接绑定(bind)ListBoxItem的IsEnabled属性:
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="IsEnabled" Value="{Binding IsEnabled}"/>
</Style>
关于c# - WPF 使用 MVVM 禁用列表框项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13769607/