WPF MVVM模式下如何禁用列表框中的项目

6
我尝试搜索了很多帖子,发现有几个与我想要的相似但并不完全符合。经过一天的搜索,我决定提问。如果我漏掉了什么,请谅解,我感觉这应该是足够常见的,但我似乎无法完全理解它。
我有一个绑定到ViewModel的UserControl,并且它有一个ListBox,ItemsSource=ObservableCollection是ViewModel的一个属性,就像下面所示:
每当我选择一个项目,我根据某些条件在其他几个项目上调用SomeObject.IsEnabled = false。我想将列表框项绑定到该IsEnabled属性,以便我可以在进行选择时使任何项目变灰。
ViewModel:
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,但我无法找到如何访问SomeObject.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>

抱歉颜色不够丰富,我是新手,不太擅长使用编辑器。
提前感谢。

你需要绑定启用属性。 - rekire
1个回答

14

{Binding IsEnabled}在你的ItemContainerStyle中应该可以完成工作。查看VS调试窗口以获取绑定错误。

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

<Style TargetType="{x:Type ListBoxItem}">
    <Setter Property="IsEnabled" Value="{Binding IsEnabled}"/>
</Style>

搞定了!我在很多示例中都看到过这个,但我意识到当我执行“Value=Binding{}”时,我期望在智能感知中看到我的IsEnabled属性,但从未看到过,因此认为我的绑定有问题。这个绑定是反射的,所以显然它不会有智能感知。现在我感觉像个白痴。 - ssj_100
1
顺便提一下:Visual Studio没有XAML绑定的智能感知功能。您需要安装插件(例如Resharper 6)才能使用。 - Federico Berasategui

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接