c# - WPF 使用 MVVM 禁用列表框项目

标签 c# wpf mvvm listbox datatrigger

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

我有一个绑定(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/

相关文章:

mvvm - 在 MVVM 应用程序中为 MEF 使用组合模型是否有好处?

c# - 尝试 socket.Connect 时出现 Socket Exception 10054

C# Excel 范围管理

c# - 使用 Roslyn 创建 Func<>

WPF 渲染颜色与画笔和控制元素的不透明度不一致

WPF DataGrid - 创建一个新的自定义列

c# - 如何使用 WriteEndElement 检查元素名称

wpf - 手动更新目标后,单向绑定(bind)停止工作

c# - WPF:Tab 的 KeyBinding,吞下 Tab 并且不传递它

wpf - 将形状添加到 Canvas 。如何绑定(bind)到虚拟机