【问题标题】:WPF: Disable items in bounded ItemsControlWPF:禁用有界 ItemsControl 中的项目
【发布时间】:2015-02-05 16:53:15
【问题描述】:

我正在使用以下内容处理 WPF 页面:

<ItemsControl ItemsSource="{Binding Peopl.PhoneNums}" x:Name="PhoneList">
 <ItemsControl.ItemTemplate>
   <DataTemplate>
     <Grid>
       <StackPanel Orientation="Horizontal" Margin="0,0,0,0" x:Name="PhoneEntry">
          <TextBlock Text="123-456-78901"/>
          <ComboBox ...>
       </StackPanel>
      </Grid>
    </DataTemplate>
  </ItemsControl.ItemTemplate>
 </ItemsControl>

可以有多个堆栈面板,每个堆栈面板都有一个唯一的电话号码;在后面的代码中,每个电话号码都有一个标志,指示是否应该启用它;我希望能够根据该标志启用堆栈面板中的每个条目,但我无法访问它......

我有:

foreach (Phone phone in PhoneList.ItemsSource)
            {
                if (phone.ShouldBeDisabled)
                {
                    int index = PhoneList.Items.IndexOf(phone);
                    PhoneList.IsEnabled = false; 
                    //this disables the entire control; 

                    // I can't access "PhoneEntry" here... hmm
                }
            }

有没有办法一次只禁用一个条目?如何访问PhoneEntry?我应该尝试根据绑定值禁用每个堆栈面板条目吗?

【问题讨论】:

  • 不要在代码中这样做。每个 PhoneEntry StackPanel 的 DataContext 都应该是您的 Phone 项。将您的禁用属性绑定到 ShouldBeDisabled 应该是答案。视图关注视图模型,视图模型不操作视图。

标签: c# wpf itemscontrol stackpanel


【解决方案1】:

您可以反转您的视图模型属性并将其命名为ShouldBeEnabled。现在您可以绑定 StackPanel 的 IsEnabled 属性了。

<StackPanel ... IsEnabled="{Binding ShouldBeEnabled}">
    ...
</StackPanel>

如果您无法更改视图模型,您可以使用反转属性值的绑定转换器:

<StackPanel ... IsEnabled="{Binding ShouldBeDisabled,
                            Converter={StaticResource InverseBooleanConverter}}">
    ...
</StackPanel>

您的 Phone 类必须实现 INotifyPropertyChanged 接口并在 ShouldBeDisabled 属性的值更改时触发 PropertyChanged 事件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-25
    • 1970-01-01
    • 2010-11-11
    • 1970-01-01
    • 1970-01-01
    • 2016-09-18
    • 1970-01-01
    相关资源
    最近更新 更多