【问题标题】:WPF Disable listbox items with MVVMWPF 使用 MVVM 禁用列表框项目
【发布时间】:2012-11-26 00:23:24
【问题描述】:

我尝试搜索了很多线程,我发现有几个非常接近但不完全是我想要的。经过一天的搜索,我决定问一下。如果我遗漏了什么,我深表歉意,我觉得这很常见,但我似乎不太明白。

我有一个绑定到 ViewModel 的 UserControl,它有一个 Listbox,其中 ItemsSource=ObservableCollection 是 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
    }
} 

对象类

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>

抱歉,缺少颜色,我是新来的,不太了解如何很好地使用编辑器。

提前致谢。

【问题讨论】:

  • 需要绑定 enabled 属性。

标签: c# wpf mvvm listbox datatrigger


【解决方案1】:

你的ItemContainerStyle 中的{Binding IsEnabled} 应该可以完成这项工作。查看 VS 调试窗口是否有绑定错误

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

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

【讨论】:

  • 做到了!我在很多示例中都看到了这一点,但我意识到当我执行“Value=Binding{}”时,我希望在智能感知中看到我的 IsEnabled 属性,并且从未假设我的绑定错误。这个绑定被反映了,所以很明显它不会有智能感知。我现在觉得自己像个白痴。
  • 顺便说一句:用于 XAML 绑定的 Intellisense 不是 Visual Studio 的特色。为此,您将需要一个插件(例如 Resharper 6)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多