C# ItemsSource的DependencyProperty
我有一个XAML,比如:C# ItemsSource的DependencyProperty,c#,wpf,dependency-properties,itemssource,C#,Wpf,Dependency Properties,Itemssource,我有一个XAML,比如: <UserControl x:Class="Book.CustomControls.HeaderedComboBox" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" DataContext="{
<UserControl x:Class="Book.CustomControls.HeaderedComboBox"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
DataContext="{Binding RelativeSource={RelativeSource Self}}"
Width="200" Height="50">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition/>
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Margin="2,2" VerticalAlignment="Center" Text="{Binding Header}" FontWeight="{Binding HeaderFontWeight}"/>
<ComboBox Grid.Row="1" Margin="2,2" VerticalAlignment="Center" ItemsSource="{Binding ItemsSource, UpdateSourceTrigger=PropertyChanged}"
SelectedItem="{Binding SelectedItem, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</Grid>
</UserControl>
我尝试在任何窗口中使用此UserControl
<customControls:HeaderedComboBox Header="Category" ItemsSource="{Binding Categories}"/>
类别只是一个可观察的集合
不幸的是,我在组合框中没有看到任何项目。目前我不知道我做错了什么。有什么想法吗
System.Windows.Data Error: 40 : BindingExpression path error: 'Categories' property not found on 'object' ''HeaderedComboBox' (Name='')'. BindingExpression:Path=Categories; DataItem='HeaderedComboBox' (Name=''); target element is 'HeaderedComboBox' (Name=''); target property is 'ItemsSource' (type 'IEnumerable')
您的DataContext设置为HeaderedCombobox,系统正在查找类别。属性头工作,因为您将文本放入其中而没有绑定。可能的解决办法
<Window x:Class="WpfApplication5.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"
xmlns:local="clr-namespace:WpfApplication5" Name="window">
<Grid>
<local:HeaderedComboBox Header="Category" ItemsSource="{Binding ElementName=window, Path=DataContext.Categories}"/>
</Grid>
<Window x:Class="WpfApplication5.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"
xmlns:local="clr-namespace:WpfApplication5" Name="window">
<Grid>
<local:HeaderedComboBox Header="Category" ItemsSource="{Binding ElementName=window, Path=DataContext.Categories}"/>
</Grid>