MKII
MKII

Reputation: 911

Binding Error 4 on ComboBox

Cannot find its cause. The code:

<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>

IsEnabled:

/// <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
      }
    }
  }

Seems fairly inoffensive, but I get error number 4 during construction, one for HorizontalContentAlignment and one for 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')

Couldn't find any solution that worked here on SO. I have tried overwritting both ListViewItem, ComboBoxItem, and ListBoxItem styles, but it doesn't work. The error itself only happens 20% of the time, which makes it harder to track. Sometimes, rarely, the error seems to happen at the end of the program (a bunch of times, 20+ times). The above is the MVCE that I could extract from the UserControl.

What is causing it?

EDIT

Full 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>

EDIT

Latest errors:

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')

I omitted repeated errors (of which I got ~20, all similar to the latter 2 up there).

Upvotes: 0

Views: 1471

Answers (1)

Bijington
Bijington

Reputation: 3751

The properties HorizontalContentAlignment and VerticalContentAlignment do not exist on ComboBoxItem or ListViewItem. You have 2 options:

  1. Set alignment on the ComboBox

Try removing these:

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

And put the following in the ComboBox element (e.g.):

<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. Set alignment as per your original approach:

Change this:

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

To:

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

Upvotes: 1

Related Questions