【问题标题】:Enable TextBox when ListViewItem is selected in WPF (databinding)在 WPF 中选择 ListViewItem 时启用 TextBox(数据绑定)
【发布时间】:2011-07-09 20:42:04
【问题描述】:

当(未)选择 ListViewItem 时,如何在 WPF 中启用/禁用带有 DataBinding 的 TextBox?

我创建了一个转换器类:

public class BoolConvert : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return value == null;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new Exception("The method or operation is not implemented.");
    }
}

并将属性添加到文本框:

IsEnabled="{Binding SelectedItem, ElementName=listViewCards, Converter={StaticResource BoolConvert}}"

但我有一个 XamlParseException 因为他找不到类:-(

【问题讨论】:

    标签: wpf data-binding listview binding textbox


    【解决方案1】:

    ListView 中的ListViewItem:

    如果选中则启用。 请尝试以下操作:

    <ListViewItem Margin="5" Background="AliceBlue">
        <TextBox Margin="5" Text="Lösung SECHS" 
            IsEnabled="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListViewItem}}, Path=IsSelected}"/>
    </ListViewItem>
    

    【讨论】:

    • 有没有办法用没有 FindAncestor 的 UWP 做到这一点?
    【解决方案2】:

    您可以将TextBox 上的IsEnabled 属性绑定到ListView 上的SelectedItem 属性。然后您需要一个转换器(IValueConverter 的实现)将选定的值转换为布尔值。

    <TextBox IsEnabled="{Binding SelectedItem, ElementName=listView, Converter={StaticResource MyConverter}}"/>
    <ListView x:Name="listView" .../>
    

    然后,在您的转换器中:

    public object Convert(object value, ...)
    {
        return value == null;
    }
    

    【讨论】:

      【解决方案3】:

      您也可以在 TextBox 上使用样式触发器,从而无需使用 ValueConverter:

      <TextBox>
         <TextBox.Style>
           <Style TargetType="{x:Type TextBox}">
             <Setter Property="IsEnabled" Value="False"/>
             <Style.Triggers>
               <DataTrigger Binding="{Binding ElementName=lvItems, Path=SelectedItem}" Value="{x:Null}">
                 <Setter Property="IsEnabled" Value="True"/>
               </DataTrigger>
             </Style.Triggers>
           </Style>
         </TextBox.Style>
      </TextBox>
      <ListView Name="lvItems" .../>
      

      【讨论】:

      • TextBox 将在您开始调试时启用,直到在 ListView 上设置 SelectedItem。你是否试图做相反的事情,只有在 ListView 中选择某些内容时才会启用 TextBox?
      • 完全正确 sry 只有在 ListView 中选择了某些内容时,才应启用 TextBox :-)
      • 没问题;如果您从我的 XAML 示例中的两个 Setter 中反转 True / False 值,我想您会得到您想要的结果。由于默认启用 TextBox,您实际上可以完全删除样式中的第一个 Setter。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-10
      • 2011-09-27
      • 1970-01-01
      • 1970-01-01
      • 2012-01-08
      相关资源
      最近更新 更多