简体   繁体   English

使用ItemSource时ComboboxItem的WPF绑定错误

[英]WPF Binding Error for ComboboxItem when using the ItemSource

I have a WPF application (.Net 4.5.1) where I create the items in a combo box dynamically, I bind to the ItemSource with an observable collection. 我有一个WPF应用程序(.Net 4.5.1),可以在组合框中动态创建项目,并使用可观察的集合绑定到ItemSource。 But when I do this i get two binding errors, one for VeticalContentAlignment and one for HorizontalContentAlignment, for each item that I add. 但是,当我这样做时,对于我添加的每个项目,我都会遇到两个绑定错误,一个是VeticalContentAlignment,一个是Horizo​​ntalContentAlignment。

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 'ComboBoxItem' (Name='PhoneItem'); 
target property is 'VerticalContentAlignment' (type 'VerticalAlignment')

I have googled and found some pointers that did not help , eg adding a global style 我用Google搜索,发现了一些三分球没有帮助 ,如添加全局样式

<Style TargetType="{x:Type ComboBoxItem}">
    <Setter Property="HorizontalContentAlignment" Value="Stretch" />
    <Setter Property="VerticalContentAlignment" Value="Center" />
 </Style>

or defining an inline container style in the combo box. 或在组合框中定义嵌入式容器样式。

<ComboBox.ItemContainerStyle>
    <Style TargetType="ComboBoxItem">
       <Setter Property="HorizontalContentAlignment" Value="Left" />
       <Setter Property="VerticalContentAlignment" Value="Center" />
    </Style>
</ComboBox.ItemContainerStyle>

I can reproduce this in a clean project where I have no styling and only a combo box bound to an observable collection if anyone is interested in having a look at my stripped code. 我可以在一个干净的项目中重现此代码,该项目没有样式,只有组合框绑定到可观察的集合,如果有人对我的剥离代码感兴趣的话。

Update 1 - My XAML and code behind 更新1-我的XAML和背后的代码

<Window x:Class="WpfApplicationDynamicComboBox.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <StackPanel>

            <Button Click="ButtonBase_OnClick" Margin="5">Load Combobox</Button>

            <ComboBox Name="DynamicComboBox"
                      ItemsSource="{Binding MyItems}"
                      Width="400"/>

        </StackPanel>
    </Grid>
</Window>


public partial class MainWindow : Window
{
  public MainWindow()
  {
    InitializeComponent();

    DataContext = this;
    MyItems = new ObservableCollection<ComboBoxItem>();
    MyItems.Add( new ComboBoxItem {Content = string.Format( "Phone: {0}", "123" ), Name = "PhoneItem_" + DateTime.Now.Second} );
  }

  public ObservableCollection<ComboBoxItem> MyItems { get; set; }

  private void ButtonBase_OnClick( object sender, RoutedEventArgs e )
  {
    MyItems.Add( new ComboBoxItem {Content = string.Format( "Phone: {0}", "123" ), Name = "PhoneItem_" + DateTime.Now.Second} );
  }
}

Update 2 - Link to sample project http://bit.ly/1fwvgkZ 更新2-链接到示例项目 http://bit.ly/1fwvgkZ

Any help getting rid of these errors are greatly appreciated! 摆脱这些错误的任何帮助将不胜感激!

Okay fixed your error. 好的,可以解决您的错误。 Just replace your code behind with 只需将您的代码替换为

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = this;

        MyItems = new ObservableCollection<ComboBoxItem>();
        MyItems.Add(new ComboBoxItem
        {
            Name = "PhoneItem_" + DateTime.Now.Second,
            Content = string.Format("Phone: {0}", "123"),
            HorizontalContentAlignment = HorizontalAlignment.Left,
            VerticalContentAlignment = VerticalAlignment.Center
        });
    }


    public ObservableCollection<ComboBoxItem> MyItems { get; set; }

    private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
    {
        MyItems.Add(new ComboBoxItem
        {
            Name = "PhoneItem_" + DateTime.Now.Second,
            Content = string.Format("Phone: {0}", "123"),
            HorizontalContentAlignment = HorizontalAlignment.Left,
            VerticalContentAlignment = VerticalAlignment.Center
        });
    }


}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM