WPF使用MVVM禁用列表框项

use*_*304 5 c# wpf listbox datatrigger mvvm

我尝试了很多线程,我发现有几个非常接近但不完全是我想要的.经过一天的搜索,我才决定问.抱歉,如果我错过了什么,我觉得这很常见,但我似乎无法得到它.

我有一个绑定到ViewModel的UserControl,它有一个带有ItemsSource = ObservableCollection的Listbox,它是ViewModel的一个属性,如下所示:

每当我选择一个项目时,我会根据某些条件在其他几个项目上调用SomeObject.IsEnabled = false.我想将列表框项绑定到该IsEnabled属性,这样每当我进行选择时,我都可以将任何项目灰显.

视图模型:

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
    }
} 
Run Code Online (Sandbox Code Playgroud)

对象类

class SomeObject : PropertyNotificationObject
{
   private bool m_isEnabled;
   public IsEnabled { get; set; } //notifying properly
}
Run Code Online (Sandbox Code Playgroud)

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}"/>
Run Code Online (Sandbox Code Playgroud)

我已尝试在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>
Run Code Online (Sandbox Code Playgroud)

抱歉没有颜色,我是新来的,不太懂得如何使用编辑器.

提前致谢.

Fed*_*gui 13

{Binding IsEnabled}ItemContainerStyle应该做的工作.查看VS调试窗口是否存在绑定错误

编辑或直接绑定ListBoxItem的IsEnabled属性:

<Style TargetType="{x:Type ListBoxItem}">
    <Setter Property="IsEnabled" Value="{Binding IsEnabled}"/>
</Style>
Run Code Online (Sandbox Code Playgroud)