【问题标题】:Binding Error 4 on ComboBox组合框上的绑定错误 4
【发布时间】:2016-06-13 10:37:37
【问题描述】:

找不到原因。代码:

<ComboBox OverridesDefaultStyle="True" MinWidth="70" MinHeight="20"
            IsSynchronizedWithCurrentItem="True" ScrollViewer.CanContentScroll="True"
            ToolTip="{Binding Text, Mode=TwoWay, ElementName=UserControl}"
            IsEditable="{Binding IsEditable, Mode=OneWay, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=local:SmartMultiTypeListView}}"
            ItemsSource="{Binding ElementName=UserControl, Path=ItemsSource}"
            DataContext="{Binding ElementName=UserControl, Path=DataContext}"
            IsEnabledChanged="OnIsEnabledChanged">
  <ComboBox.ItemContainerStyle>
    <Style TargetType="{x:Type ComboBoxItem}">
      <Setter Property="HorizontalContentAlignment" Value="Left" />
      <Setter Property="VerticalContentAlignment" Value="Center" />
    </Style>
  </ComboBox.ItemContainerStyle>
</ComboBox>

已启用:

/// <summary>
/// Used to handle when the combobox is enabled/disabled
/// </summary>
private void OnIsEnabledChanged (object Sender, DependencyPropertyChangedEventArgs E)
  {
  if ((bool)E.NewValue == true)
    {
    ComboBox CBox = Sender as ComboBox;
    if (CBox != null)
      {
      IEnumerable LastBinding = CBox.ItemsSource; // Store old binding
      CBox.ItemsSource = null; // Forces refresh/rebinding
      CBox.ItemsSource = LastBinding; // Reset binding by rebinding the old value
      }
    }
  }

看起来相当无害,但我在构建过程中收到错误号 4,一个是 HorizontalContentAlignment,一个是 VerticalContentAlignment

System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.ItemsControl', AncestorLevel='1''. BindingExpression:Path=HorizontalContentAlignment; DataItem=null; target element is 'ListViewItem' (Name=''); target property is 'HorizontalContentAlignment' (type 'HorizontalAlignment')

找不到任何适用于 SO 的解决方案。我尝试过覆盖ListViewItemComboBoxItemListBoxItem 样式,但它不起作用。错误本身只发生 20% 的时间,这使得跟踪变得更加困难。有时,错误似乎很少发生在程序结束时(很多次,20 多次)。以上是我可以从UserControl中提取的MVCE。

是什么原因造成的?

编辑

完整的 XAML:

  <ComboBox OverridesDefaultStyle="True" MinWidth="70" MinHeight="20"
            IsSynchronizedWithCurrentItem="True" ScrollViewer.CanContentScroll="True"
            ToolTip="{Binding Text, Mode=TwoWay, ElementName=UserControl}"
            IsEditable="{Binding IsEditable, Mode=OneWay, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=local:SmartMultiTypeListView}}"
            ItemsSource="{Binding ElementName=UserControl, Path=ItemsSource}"
            DataContext="{Binding ElementName=UserControl, Path=DataContext}"
            HorizontalContentAlignment="Left"
            VerticalContentAlignment="Center"
            IsEnabledChanged="OnIsEnabledChanged">
    <ComboBox.ItemContainerStyle>
      <Style TargetType="{x:Type ComboBoxItem}">
        <Setter Property="HorizontalAlignment" Value="Left" />
        <Setter Property="VerticalAlignment" Value="Center" />
      </Style>
    </ComboBox.ItemContainerStyle>

    <ComboBox.ItemTemplate>
      <HierarchicalDataTemplate>
        <CheckBox Content="{Binding Name}" Margin="2" IsChecked="{Binding IsChecked, Mode=TwoWay}"
                  IsEnabled="{Binding IsEnabled}" Tag="{RelativeSource FindAncestor, AncestorType={x:Type ComboBox}}" />
      </HierarchicalDataTemplate>
    </ComboBox.ItemTemplate>

    <ComboBox.Template>
      <ControlTemplate TargetType="ComboBox">
        <Grid>
          <ToggleButton Grid.Column="2" Focusable="False"
                        IsChecked="{Binding Path=IsDropDownOpen, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
                        ClickMode="Press"/>

          <ContentPresenter x:Name="Presenter" IsHitTestVisible="False" Margin="3, 3, 23, 3" VerticalAlignment="Center" 
                            HorizontalAlignment="Left" >
            <ContentPresenter.Content>
              <TextBlock TextTrimming="CharacterEllipsis" Foreground="Black"
                         Text="{Binding Path=Text, Mode=TwoWay, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}}" />
            </ContentPresenter.Content>
          </ContentPresenter>

          <TextBox x:Name="EditableTextBox" Style="{x:Null}" HorizontalAlignment="Left" 
                   VerticalAlignment="Center" Margin="3, 3, 23, 3" Focusable="True" Background="Transparent" Visibility="Hidden"
                   IsReadOnly="{TemplateBinding IsReadOnly}" />

          <Popup x:Name="Popup" Placement="Bottom" IsOpen="{TemplateBinding IsDropDownOpen}" AllowsTransparency="True"
                 Focusable="False" PopupAnimation="None">
            <Grid SnapsToDevicePixels="True" MinWidth="{TemplateBinding ActualWidth}" MaxHeight="{TemplateBinding MaxDropDownHeight}">
              <Border x:Name="DropDownBorder" Background="{StaticResource WindowBackgroundBrush}" BorderThickness="1" 
                      BorderBrush="#444" />
              <ScrollViewer Margin="4, 6, 4, 6" SnapsToDevicePixels="True" DataContext="{Binding}">
                <StackPanel IsItemsHost="True" KeyboardNavigation.DirectionalNavigation="Contained" />
              </ScrollViewer>
            </Grid>
          </Popup>
        </Grid>

        <ControlTemplate.Triggers>
          <Trigger Property="HasItems" Value="false">
            <Setter TargetName="DropDownBorder" Property="MinHeight" Value="95" />
          </Trigger>
          <Trigger Property="IsEnabled" Value="false">
            <Setter Property="Foreground" Value="{StaticResource DisabledForegroundBrush}" />
          </Trigger>
          <Trigger Property="IsGrouping" Value="true">
            <Setter Property="ScrollViewer.CanContentScroll" Value="false" />
          </Trigger>
          <Trigger SourceName="Popup" Property="Popup.AllowsTransparency" Value="true">
            <Setter TargetName="DropDownBorder" Property="Margin" Value="0, 2, 0, 0" />
          </Trigger>
          <Trigger Property="IsEditable" Value="False">
            <Setter Property="IsEnabled" Value="False" />
            <Setter Property="IsTabStop" Value="False" />
            <Setter TargetName="EditableTextBox" Property="Visibility" Value="Visible" />
            <Setter TargetName="Presenter" Property="Visibility" Value="Hidden" />
          </Trigger>
        </ControlTemplate.Triggers>
      </ControlTemplate>
    </ComboBox.Template>
  </ComboBox>

编辑

最新错误:

System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.ItemsControl', AncestorLevel='1''. BindingExpression:Path=HorizontalContentAlignment; DataItem=null; target element is 'ListViewItem' (Name=''); target property is 'HorizontalContentAlignment' (type 'HorizontalAlignment')

System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.ItemsControl', AncestorLevel='1''. BindingExpression:Path=VerticalContentAlignment; DataItem=null; target element is 'ListViewItem' (Name=''); target property is 'VerticalContentAlignment' (type 'VerticalAlignment')

System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.ItemsControl', AncestorLevel='1''. BindingExpression:Path=HorizontalContentAlignment; DataItem=null; target element is 'ListBoxItem' (Name=''); target property is 'HorizontalContentAlignment' (type 'HorizontalAlignment')

System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.ItemsControl', AncestorLevel='1''. BindingExpression:Path=VerticalContentAlignment; DataItem=null; target element is 'ListBoxItem' (Name=''); target property is 'VerticalContentAlignment' (type 'VerticalAlignment')

我省略了重复的错误(我得到了大约 20 个,都与上面的后 2 个相似)。

【问题讨论】:

  • 出于兴趣,为什么每次 IsEnabled 更改时都刷新 ItemsSource?
  • 我想这是由于以下情况引起的: 您的 Itemscontrol 在组合框之后呈现。此代码导致错误:sEditable="{Binding IsEditable, Mode=OneWay, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=local:SmartMultiTypeListView}}"。确保也有一个父项控件

标签: c# wpf xaml data-binding combobox


【解决方案1】:

HorizontalContentAlignmentVerticalContentAlignment 属性在 ComboBoxItemListViewItem 上不存在。你有两个选择:

  1. ComboBox 上设置对齐

尝试删除这些:

<Setter Property="HorizontalContentAlignment" Value="Left" />
<Setter Property="VerticalContentAlignment" Value="Center" />

并将以下内容放入 ComboBox 元素中(例如):

<ComboBox OverridesDefaultStyle="True" MinWidth="70" MinHeight="20"
        IsSynchronizedWithCurrentItem="True" ScrollViewer.CanContentScroll="True"
        ToolTip="{Binding Text, Mode=TwoWay, ElementName=UserControl}"
        IsEditable="{Binding IsEditable, Mode=OneWay, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=local:SmartMultiTypeListView}}"
        ItemsSource="{Binding ElementName=UserControl, Path=ItemsSource}"
        DataContext="{Binding ElementName=UserControl, Path=DataContext}"
        IsEnabledChanged="OnIsEnabledChanged"

        HorizontalContentAlignment="Left"
        VerticalContentAlignment="Center">
  1. 按照您原来的方法设置对齐方式:

改变这个:

<Setter Property="HorizontalContentAlignment" Value="Left" />
<Setter Property="VerticalContentAlignment" Value="Center" />

收件人:

<Setter Property="HorizontalAlignment" Value="Left" />
<Setter Property="VerticalAlignment" Value="Center" />

【讨论】:

  • @MKII 不确定在没有看到更多真实代码的情况下我还能做些什么来提供帮助。两个版本的代码之间一定有什么缺失的地方。
  • @MKII 我可以检查一下问题是您仍然看到绑定错误吗?
  • 是的。我将在最新测试运行中遇到的错误添加到主帖中。 ListViewItem 错误在启动时发生。查看控件时出现 ListBoxItem 错误。
  • @MKII 您的应用程序中是否还有其他部分可以引用ListViewItemListBoxItem。我的第一个猜测是在您提供的代码之外的其他地方出了问题。
  • 只有 2 个其他地方引用了 ListViewItem,两者都很短 Styles 主要用于为项目的行提供交替颜色。 ListBoxItem 仅在几个地方使用,如果我将它们注释掉,就会发生错误。此外,ListBoxItem 错误仅在自定义 ComboBox 进入视图时发生。如果我从项目中删除了自定义 ComboBox,所有错误都会停止发生。
猜你喜欢
  • 1970-01-01
  • 2020-02-14
  • 2014-02-09
  • 2014-01-11
  • 2011-12-14
  • 1970-01-01
  • 2013-06-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多